二维数组成一个对象

时间:2015-10-05 22:04:32

标签: javascript arrays object

基本上,我想:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']
];

进入这个:

var current = {
    socks: 4,
    pants: 2,
    shoes: 1,
    hats: 5
};

3 个答案:

答案 0 :(得分:3)

如果您想迭代一个集合并返回一个对象,那么reduce()就是您的工具:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']];

current.reduce(
   function(m,c) { 
       m[c[1]] = c[0]; 
       return m;
   }, {})

// Object {socks: 4, pants: 2, shoes: 1, hats: 5}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

答案 1 :(得分:2)

您可以循环遍历数组中的数组,并将它们作为属性添加到对象中:

var result = {};
for (var i = 0; i < current.length; i++) {
  result[current[i][1]] = current[i][0];
}

演示:

var current = [
    [4, 'socks'],
    [2, 'pants'],
    [1, 'shoes'],
    [5, 'hats']];

var result = {};
for (var i = 0; i < current.length; i++) {
     result[current[i][1]] = current[i][0];
}

// show result in snippet
document.write(JSON.stringify(result));

答案 2 :(得分:1)

使用[].forEach.call()

&#13;
&#13;
 var current = [
   [4, 'socks'],
   [2, 'pants'],
   [1, 'shoes'],
   [5, 'hats']
 ];

 var res = {};

 [].forEach.call(current, function(el) {
   res[el[1]] = el[0];
 });

console.log(res);

var html = document.getElementById("result");
result.innerHTML = JSON.stringify(res);
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;