如何将嵌套数组转换为对象

时间:2018-03-03 03:30:35

标签: javascript object for-loop

我想从嵌套数组中创建一个只有2级深度的对象。我想出的功能返回

[{ key1: 'value1', key2: 'value2' }]

而不是

[{ key1: 'value1' }, {key2: 'value2' }]

我也尝试用obj[elem[0]] = elem[1];替换if语句,但得到相同的结果。

如何为每个嵌套数组创建单独的对象?

var array = [["key1", "value1"], ["key2", "value2"]]

function nestedArrToObj(array){

  let obj = {};

  for (let i=0; i < array.length;i++) {
    let elem = array[i];

    if (!(obj[elem[0]])) {
      obj[elem[0]] = elem[1]
    }
  }

  return [obj];
}

3 个答案:

答案 0 :(得分:2)

使用函数map

&#13;
&#13;
let array = [["key1", "value1"], ["key2", "value2"]];
let result = array.map(([key, value]) => ({[key]: value}));

console.log(result)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

使用函数reduce

&#13;
&#13;
let array = [["key1", "value1"], ["key2", "value2"]];
let result = array.reduce((a, c) => {
  let [key, value] = c;
  return [...a, {[key]: value}];
}, []);

console.log(result)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

跨浏览器和后端技术兼容的方法:

&#13;
&#13;
var array = [["key1", "value1"], ["key2", "value2"]];

var result = [];
for(var a of array) {
  var value = a.pop();
  var key = a.pop();
  
  var object = {};
  object[key] = value;
  
  result.push(object);
}

console.log(result)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个map的版本:

&#13;
&#13;
console.log(
  [["key1", "value1"], ["key2", "value2"]]
      .map(x => {let obj = {}; obj[x[0]] = x[1]; return obj;})
)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

该语言的一些较新功能使这更容易一些。这是一个ES5解决方案。

var array = [["key1", "value1"], ["key2", "value2"]]

function nestedArrToObj(array){
  return array.reduce(function(previous, current) {
      let obj = {};
      obj[current[0]] = current[1];
      previous.push(obj);
      return previous;
  }, []);
}

console.log(nestedArrToObj(array))