[英]Loop through each object of an array and append each object from second array to the first array
I have two arrays of objects.我有两个 arrays 对象。 I need to loop through the first array and append each object of the second array to each object of the first array.我需要遍历第一个数组和 append 第二个数组的每个 object 到第一个数组的每个 object 。
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.一个循环加上 Object.assign() 我相信这就是你要找的。
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:由于结果是一个全新的数组,您可以使用Array#map
- 它创建一个新数组,并使用扩展运算符如下:
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.