猿问

如何添加值并嵌套对象

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成为动态的吗?


当年话下
浏览 154回答 1
1回答

皈依舞

您可以使用ES6 的计算名称属性通过简单地用括号包裹来从变量设置属性名称。const arr = [&nbsp; [1, "string1", 'string11'],&nbsp; [2, "string2", 'string22'],&nbsp; [3, "string3", 'string33'],&nbsp; [4, "string4", 'string44'],];const obj = arr.reduce((acc, val) => {&nbsp; for (let i = 0; i < val.length; i += 3) {&nbsp; &nbsp; acc[val[i]] = {&nbsp; &nbsp; &nbsp; [val[i + 1]]: val[i + 2]&nbsp; &nbsp;//-^^^^^^^^^^^^---- here&nbsp; &nbsp; }&nbsp; }&nbsp; return acc;}, {});console.log(obj);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答