如何在JavaScript中将格式更改为数组?

时间:2014-03-27 10:21:24

标签: javascript arrays

我正在以这种格式获得一些价值

 [["first"],["second"],["third"]]

我希望得到

 {"first","second","third"}

我应该在javascript中做什么?

1 个答案:

答案 0 :(得分:0)

这是非法的:{"first","second","third"}

对象必须是键值对的映射。你能做到的最好的就是:

{`first`: null, `second`: null, `third`: null}

JSFiddle DEMO

var arr2d = [["first"], ["second"], ["third"]];
var arrFlat = arr2d.reduce(function(a, b) {
    return a.concat(b);
});

var obj = {};
for (var i = 0; i < arrFlat.length; i++) {
    obj[arrFlat[i]] = null;
}

console.log(obj);