I have an object like this
let obj = {
"apple": {
"color": "red",
},
"banana": {
"color": "yellow"
}
}
I am getting an array of objects of this form
let arr = [
{
"count": "9904",
"fruit": "apple",
"type": "typea"
},
{
"count": "7142",
"fruit": "banana",
"type": "typeb"
},
{
"count": "4121",
"fruit": "apple",
"type": "typec"
}
]
I want to combine these two so that each item in objcan have variable no of properties so that final output look something like this
{
"apple": {
"color": "red",
"typea": "9904",
"typec": "4121"
},
"banana": {
"color": "yellow",
"typeb": "7142"
}
}
I tried running the array through a for loop but when I try to use the dynamic values in keys it shows error
for (let item of arr){
obj[item.fruit] = {...obj[item.fruit], item.type: item.count}
}
If instead of item.type I put some static value like "count" it works but I can't figure out how to use dynamic value
Can anyone suggest me what is the best way to accomplish this?