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
动态吗?
答案 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);