gpt4 book ai didi

javascript - 将一组对象转换为一个对象对象

转载 作者:行者123 更新时间:2023-12-03 01:40:13 24 4
gpt4 key购买 nike

如何将一组对象转换为一个对象对象。我的函数可以工作,但我不希望每个对象之前都有键名称。

 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"
}{

最佳答案

对象是属性的集合,属性是名称(或键)与值之间的关联。

您可以使用索引作为键或属性名称。使用Object.assign创建一个新对象。使用 map 和 spread 语法循环遍历数组。

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);

文档:Objects

关于javascript - 将一组对象转换为一个对象对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50878985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com