gpt4 book ai didi

javascript - JS 将数组转换为对象,然后用属性值替换对象键

转载 作者:行者123 更新时间:2023-11-28 13:01:46 24 4
gpt4 key购买 nike

我需要将数组转换为对象,然后需要将对象属性值之一移动为对象属性键名称:

[
{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type":"fruit",
"item": "banana"
}
]

进入

{
"apple": {
"description": "red",
"type": "fruit"
},
"banana": {
"description": "yellow",
"type": "fruit"
}
}

使用Object.assign({}, ...arr)将对象的名称填充到索引中,我需要更改该索引,谢谢!

最佳答案

您可以使用Array#reduce将数组折叠成一个对象。使用解构,您可以从对象中提取值,并以所需的输出格式创建一个新对象。

const data = [
{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type":"fruit",
"item": "banana"
}
]

console.log(
data.reduce((accumulator, { item, description, type }) => ({
...accumulator,
[item]: { description, type }
}), {})
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

关于javascript - JS 将数组转换为对象,然后用属性值替换对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49785571/

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