简体   繁体   中英

Loop through each object of an array and append each object from second array to the first array

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.

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())

 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);

 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);

Since the result is a completely new array, you can use Array#map - which creates a new array, and the spread operator as follows:

 const productsArray = [ {Name: 'product1', SKU: 'sku1'}, {Name: 'product2', SKU: 'sku2'}, {Name: 'product3', SKU: 'sku3'} ]; const quantitiesArray = [ {Quantity: 100}, {Quantity: 300}, {Quantity: 600} ]; const newProductsArray = productsArray.map( (prodArr,i) => ({...prodArr, ...quantitiesArray[i]}) ) console.log( newProductsArray );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM