I have 2 objects, as such:
costsObj = {
Honda: 24000,
BMW: 55000,
Toyota: 22000
};
stockObj = {
Honda: 5,
BMW: 1,
Toyota: 2
}
I want to combine the 2 objects into 1 array of objects that looks like:
carsArr = [
{brand: "Honda", cost: 24000, stock: 5},
{brand: "BMW", cost: 55000, stock: 1},
{brand: "Toyota", cost: 22000, stock: 2}
]
I have achieved this by using map(), for(), and forEach():
// Use costsObj to create new array
carsArr = Object.keys(costsObj).map(brand => {
return { brand, cost: costsObj[brand], stock: 0 };
});
// Add data from stockObj to new carsArr
for (const [key, value] of Object.entries(stockObj)) {
carsArr.forEach((item, index)=>{
if(item.term == key) {
carsArr[index].stock = value;
}
})
};
But this feels clunky and that there could/should be a better way, especially if I want to combine data from more objects in the future, eg:
carsArr = [
{brand: "Honda", model: "Accord", cost: 24000, stock: 5},
{brand: "BMW", model: "3 series", cost: 55000, stock: 1},
{brand: "Toyota", model: "Camry", cost: 22000, stock: 2}
]
Does anyone know if there is a better way to combine the data from many objects into one array of objects?