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: Objectval: "string11"2: Objectval: "string22"3: Objectval: "string33"4: Objectval: "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 回答
皈依舞
TA贡献1851条经验 获得超3个赞
您可以使用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);
添加回答
举报
0/150
提交
取消