我想要像
这样的对象var obj = {
"ABC" : { name: true, dob: true},
"CDE" : { name: true, dob: true},
"EFG" : { name: true, dob: true},
"CBA" : { name: true, dob: true},
"XYZ" : { name: true, dob: true},
}
var arr = ["ABC","CDE","EFG","CBA","XYZ"];
我尝试用
添加它newArray.push({
key: arr[i],
name: true,
dob: true
});
var newObj = {}
newObj[i] = newArray;
但我无法将此作为整个对象传递给我的代码。当我将其字符串化时,它返回
{
'0':"[{
key: "ABC",
name: true,
dob: true
},{
key: "CDE",
name: true,
dob: true
}]"
}
答案 0 :(得分:4)
您可以使用(rn - 1) / 2
创建对象。使用扩展运算符和Object.assign
重复数组。
map
另一个选择是使用var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"];
var obj = Object.assign(...arr.map(o => ({[o]: {name: true,dob: true}})));
console.log(obj);
将数组转换为有效对象。
reduce
答案 1 :(得分:1)
var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"];
var obj = arr.reduce((c, v) => Object.assign(c, {[v]: {name: true,dob: true}}), {});
console.log(obj);
答案 2 :(得分:1)
var arr = ["ABC","CDE","EFG","CBA","XYZ"];
let obj = {};
arr.forEach(x=> {
obj[x] = {
name: true,
dob: true
}
});
console.log(obj)
循环通过数组,为每个元素使用它作为键并添加一个对象作为值
答案 3 :(得分:0)
var objStr = '{'
var arr = ["ABC", "CDE", "EFG", "CBA", "XYZ"],
propertyValue = ':{"name":true,"dob":true}'
for (var x in arr) {
if (x < arr.length - 1)
objStr += '"' + arr[x] + '"' + propertyValue + ','
else
objStr += '"' + arr[x] + '"' + propertyValue
}
objStr += '}'
console.log(JSON.parse(objStr))
&#13;
希望这可以帮助你:)