2

比如说我有一个如下的对象图:

{
    "key1" : { data: "data1", extra: "none" },
    "key2" : { data: "data2", extra: "none" },
    "key3" : { data: "data3", extra: "none" },
    "key4" : { data: "data4", extra: "none" }, 
};

有没有一种方便的方法可以将其转换为多维数组,如下所示:

[
    [ "key1" , { data: "data1", extra: "none" } ],
    [ "key2" , { data: "data2", extra: "none" } ],
    [ "key3" , { data: "data3", extra: "none" } ],
    [ "key4" , { data: "data4", extra: "none" } ], 
];

我有一个需要数组的函数,但我从 3rd 方插件接收的数据位于对象数组中。如果有一些简单的方法可以在两者之间完成转换,那就太好了。

4

3 回答 3

5

试试这个功能:

function convert(original) {
    var multiArray = [];
    for(var key in original) { multiArray.push([ key, original[key] ]); }
    return multiArray;
}

请参阅演示小提琴

像这样使用它:

var myObject = {
    "key1" : { data: "data1", extra: "none" },
    "key2" : { data: "data2", extra: "none" },
    "key3" : { data: "data3", extra: "none" },
    "key4" : { data: "data4", extra: "none" }, 
};
var myMultiArray = convert(myObject);
于 2013-05-18T06:30:46.457 回答
3

如果您制作pair如下所示的辅助函数,那么标准键/映射就足够了:

Object.keys(m).map(pair.bind(m))
function pair(x){return [x, this[x]]}
于 2013-05-18T06:39:05.167 回答
3

在 ES6 中,它就像[[e, o[e]] for (e in o)].

于 2013-05-18T16:22:21.877 回答