如何添加值和嵌套对象

时间:2019-08-20 08:00:29

标签: javascript

const arr = [
  [1, "string1", 'string11'],
  [2, "string2", 'string22'],
  [3, "string3", 'string33'],
  [4, "string4", 'string44'],
];
const obj = arr.reduce((acc, val) => {
  for (let i = 0; i < val.length; i += 3) {
    acc[val[i]] = {
      val: val[i + 2]
    }
  }
  return acc;
}, {});
console.log(obj);

output is :
1: Object
val: "string11"
2: Object
val: "string22"
3: Object
val: "string33"
4: Object
val: "string44"

我想将val: val[i+2]替换为val[i+1]: val[i+2]以使对象成为

1: Object
"string1": "string11"
2: Object
"string2": "string22"
3: Object
"string3": "string33"
4: Object
"string4": "string44"

但是此语法不正确val[i+1]: val[i+2],有人可以告诉我如何使val动态吗?

1 个答案:

答案 0 :(得分:2)

您可以使用compute name property of ES6来设置变量的属性名称,只需用括号括起来即可。

const arr = [
  [1, "string1", 'string11'],
  [2, "string2", 'string22'],
  [3, "string3", 'string33'],
  [4, "string4", 'string44'],
];
const obj = arr.reduce((acc, val) => {
  for (let i = 0; i < val.length; i += 3) {
    acc[val[i]] = {
      [val[i + 1]]: val[i + 2]
   //-^^^^^^^^^^^^---- here
    }
  }
  return acc;
}, {});
console.log(obj);