如何将对象数组转换为对象的一个对象。我的功能有效但我不想在每个对象之前使用键名。
myArray = [{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}]
let result = {};
for (let item of seriesTotal) {
result[item.name] = item;
delete item.name;
}
我想要这个
myObject = {{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}{
答案 0 :(得分:1)
对象是属性的集合,属性是名称(或键)与值之间的关联。
您可以使用索引作为键或属性名称。使用Object.assign
创建新对象。使用map
和扩展语法循环遍历数组。
let myArray = [{
"name": "ann",
"y": 191,
"color": "red"
}, {
"name": "mary",
"y": 11,
"color": "red"
}, {
"name": "henry",
"y": 11,
"color": "red"
}];
let result = Object.assign(...myArray.map((o,i) => ({[i]: o})));
console.log(result);
Doc:Objects
答案 1 :(得分:0)
由于您想要的是无效的JS对象,您将在JS中获取一个字符串,因此您可以使用.replace()
:
myArray = JSON.stringify(myArray).replace(/(\[)(.+)(\])/g,"{$2}");
console.log(myArray);
//{{"name":"ann","y":191,"color":"red"},{"name":"mary","y":11,"color":"red"},{"name":"henry","y":11,"color":"red"}}
但正如我之前所说,那不是JS对象,它只是一个字符串。