我正在使用Reactjs Web应用程序,我有一个类似
的数组let arr = ["name","message", etc...];
我想将其转换为对象,但看起来像
let desired = { name:'', message:'' };
我尝试了一些方法,但是没有一个起作用。
答案 0 :(得分:3)
如果只想为数组中的每个值分配一个空字符串的值,请使用reduce
:
let arr = ["name","message", "etc"];
let desired = arr.reduce((acc, curr) => (acc[curr] = "", acc), {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5语法:
var arr = ["name","message", "etc"];
var desired = arr.reduce(function(acc, curr) {
acc[curr] = "";
return acc;
}, {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 1 :(得分:1)
尝试一下:
let arr = ["name","message", "etc"];
let desired = {};
for (let i = 0; i < arr.length; i++) {
desired[arr[i]] = "";
}
console.log(desired);
答案 2 :(得分:0)
您也可以使用forEach()
let arr = ['name', 'type', 'id', 'phone'];
let obj = {};
arr.forEach(i=>{obj[i] = ''});
console.log(obj);