I have an array of objects who all share keys with the same name, products
... I am having trouble bringing all of the values under the first products
key, and removing the other two products
keys. I have tried various methods using unshift()
, but keep messing it up. What's the most efficient and simple way to restructure the array.
What it looks like now:
[ { products:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
{ products:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] },
{ products:
[ [Object],
[Object],
[Object],
[Object] ] } ]
What it should look like
[ { products: [Object], [Object], etc...
Your desired output is wrongly formatted, but from the description I get you want one array with product objects. I don't think it is necessary then to still have that joined array in an object, which again sits in an array with just that one object.
So, just make it one array, and assign it to a products
variable. You can use flatMap
for this:
let arr = [ { products: [{a: 1}, {b: 2}] }, { products: [{c: 3}, {d: 4}] }, { products: [{e: 5}, {f: 6}] } ]; let products = arr.flatMap(({products}) => products); console.log(products); // If you REALLY need it in an array with one object: let obese = [{products}]; console.log(obese);
Since your desired output is not valid JavaScript, I extrapolated a valid syntax:
const ary = [{products: ['a', 'b', 'c']}, {products: ['m', 'n']}, {products: ['x', 'y']}];
const result = {products: ary.reduce((accum, obj) => [...accum, ...obj.products], [])};
console.log(result) // output => {products: ['a', 'b', 'c', 'm', 'n', 'x', 'y']}
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.