我有一个这样的物体
let obj = {
"apple": {
"color": "red",
},
"banana": {
"color": "yellow"
}
}
我得到了这种形式的对象的数组
let arr = [
{
"count": "9904",
"fruit": "apple",
"type": "typea"
},
{
"count": "7142",
"fruit": "banana",
"type": "typeb"
},
{
"count": "4121",
"fruit": "apple",
"type": "typec"
}
]
我想将两者结合起来,以便其中的每个项目都obj
可以具有可变的属性编号,以便最终输出看起来像这样
{
"apple": {
"color": "red",
"typea": "9904",
"typec": "4121"
},
"banana": {
"color": "yellow",
"typeb": "7142"
}
}
我尝试通过for循环运行数组,但是当我尝试在键中使用动态值时,它显示错误
for (let item of arr){
obj[item.fruit] = {...obj[item.fruit], item.type: item.count}
}
如果不是item.type
我放一些静态值"count"
就可以了,但我不知道如何使用动态值
谁能建议我实现这一目标的最佳方法是什么?
您应该在方括号中使用计算的属性名称。
let obj = {
"apple": {
"color": "red",
},
"banana": {
"color": "yellow"
}
}
let arr = [
{
"count": "9904",
"fruit": "apple",
"type": "typea"
},
{
"count": "7142",
"fruit": "banana",
"type": "typeb"
},
{
"count": "4121",
"fruit": "apple",
"type": "typec"
}
]
for (let item of arr){
obj[item.fruit] = {...obj[item.fruit], [item.type]: item.count}
}
console.log(obj);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句