I have two arrays of objects. I need to loop through the first array and append each object of the second array to each object of the first array.
First array:
const productsArray = [
{Name: 'product1', SKU: 'sku1'},
{Name: 'product2', SKU: 'sku2'},
{Name: 'product3', SKU: 'sku3'}
];
Second Array:
const quantitiesArray = [
{Quantity: 100},
{Quantity: 300},
{Quantity: 600}
];
Desired Outcome:
const newProductsArray = [
{Name: 'product1', SKU: 'sku1', Quantity: 100},
{Name: 'product2', SKU: 'sku2', Quantity: 300},
{Name: 'product3', SKU: 'sku3', Quantity: 600}
]
There will always be the same amount of objects in each array.
CodePudding user response:
This should point you in the right direction. A loop plus Object.assign() I believe is what you're looking for.
const productsArray = [{
Name: 'product1',
SKU: 'sku1'
},
{
Name: 'product2',
SKU: 'sku2'
},
{
Name: 'product3',
SKU: 'sku3'
}
];
const quantitiesArray = [{
Quantity: 100
},
{
Quantity: 300
},
{
Quantity: 600
}
];
function appendArray() {
let assignedArray;
for (let i = 0; i < productsArray.length; i ) {
assignedArray = Object.assign(productsArray[i], quantitiesArray[i])
}
return assignedArray;
}
console.log(appendArray())
CodePudding user response:
const productsArray = [
{Name: 'product1', SKU: 'sku1'},
{Name: 'product2', SKU: 'sku2'},
{Name: 'product3', SKU: 'sku3'}
], quantitiesArray = [
{Quantity: 100},
{Quantity: 300},
{Quantity: 600}
];
const res=quantitiesArray.map((q,i)=>(
{...productsArray[i],...q}
))
console.log(res);
CodePudding user response:
const productsArray = [
{Name: 'product1', SKU: 'sku1'},
{Name: 'product2', SKU: 'sku2'},
{Name: 'product3', SKU: 'sku3'}
];
const quantitiesArray = [
{Name: 'product1', SKU: 'sku1', Quantity: 100},
{Name: 'product2', SKU: 'sku2', Quantity: 300},
{Name: 'product3', SKU: 'sku3', Quantity: 600}
];
const newProductsArray = [];
productsArray.forEach((item,index) => {
newProductsArray.push({...item,...quantitiesArray[index]});
});
console.log(newProductsArray);