By making two api calls receive two types of data as follows :
(1) array of Objects
[
{ label: "Private", price: 5 },
{ label: "VIP", price: 5 },
];
(2) Object >>>>> {}
{
"Private": {
"count": 34
},
"VIP": {
"count": 80
}
}
How do I merge this data depending on the label to be as follows
[
{ label: "Private", price: 5, count: 34 },
{ label: "VIP", price: 5, count: 80 },
]
Thank you
>Solution :
Here is an easy way to merge those two into a new array of objects while not mutating your initial query results.
const array = [
{label: "Private", price: 5},
{label: "VIP", price: 5}
];
const object = {
"Private": {"count": 34},
"VIP": {"count": 80}
};
function merge(arr, obj) {
// Create new array to avoid mutating initial query result
const newArray = structuredClone(arr);
newArray.forEach(item => {
// Make sure obj has the label
if (obj[item.label]) {
// Simply assign the count by using key accessor syntax []
item.count = obj[item.label].count;
}
});
return newArray;
}
console.log(merge(array, object));