简体   繁体   English

以最有效的方式重构 JavaScript 对象数组

[英]Restructuring JavaScript array of objects in the most efficient way

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.我有一组对象,它们都共享具有相同名称的键、 products ……我无法将所有值放在第一个products键下,并删除其他两个products键。 I have tried various methods using unshift() , but keep messing it up.我尝试过使用unshift()各种方法,但一直搞砸了。 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.因此,只需将其设为一个数组,并将其分配给products变量。 You can use flatMap for this:您可以为此使用flatMap

 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:由于您想要的输出不是有效的 JavaScript,我推断出一个有效的语法:

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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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