如何在javascript中的任何级别将对象数组与属性合并?

如何在javascript中的任何级别将对象数组与属性合并?,javascript,ecmascript-6,lodash,Javascript,Ecmascript 6,Lodash,这是我的数组对象 var skus = [ { "id": "1", "active": true, "attributes": { "color": "pink", "size": "small", "material": "plastic" }, "price": 899 },{ "id": "2", "object": "sku", "active": true, "attr

这是我的数组对象

var skus = [
  {
    "id": "1",
    "active": true,
    "attributes": {
      "color": "pink",
      "size": "small",
      "material": "plastic"
    },
    "price": 899
  },{
    "id": "2",
    "object": "sku",
    "active": true,
    "attributes": {
      "color": "blue",
      "size": "medium",
      "material": "plastic"
    },
    "price": 500
  },{
    "id": "3",
    "object": "sku",
    "active": true,
    "attributes": {
      "color": "blue",
      "size": "medium",
      "material": "metal"
    },
    "price": 600
  }
]
我希望输出如下所示:

finalOutput = {
  "plastic" : [{id:1,...},{id:2,...}],
  "metal" : [{id:3,...}]
}
因此,基本上,我想合并所有具有相同属性的对象。材质值。

使用lodash的属性来收集对象。材质

var skus=[{“id”:“1”,“active”:true,“attributes”:{“color”:“pink”,“size”:“small”,“material”:“plastic”},“price”:899},{“id”:“2”,“object”:“sku”,“active”:true,“attributes”:{“color”:“blue”,“size”:“medium”,“material”:“plastic”},“price”:500},{“id”:“3”,“object”:“sku”,“active”:true,“attributes”:{“color”:“color”:“blue”:“size”:“size”:“medium”,“material”:“metal”},“价格”:600}];
var结果=u.groupBy(SKU,'attributes.material');
console.log(结果);

…好的,让我们看看

var skus=[{“id”:“1”,“active”:true,“attributes”:{“color”:“pink”,“size”:“small”,“material”:“plastic”},“price”:“899},{“id”:“2”,“object”:“sku”,“active”:true,“attributes”:{“color”:“blue”,“size”:“medium”,“material”:“plastic”},“price”:“500},{“id”:“3”,“object”:“sku”,“active”:true,“attributes”:{“color”:蓝色“,”尺寸“:”中等“,”材料“:”金属“}”,价格“:”600}];
var obj={};
SKU.forEach(o=>{
如果(!obj.hasOwnProperty(o.attributes.material)){
对象[o.属性.材质]=[o];
}否则{
对象[o.attributes.material].push(o);
}
});
console.log(obj);

.as控制台包装{最大高度:100%!重要;顶部:0;}
欢迎来到Stack Overflow!请通读,尤其是做你的研究。有关这方面的相关主题,请尝试做这项工作。如果你在做了更多的研究和搜索后陷入困境,无法摆脱困境,请发布你的尝试,并明确说明你的困境。(不是我的dv)@NinaScholz没有。我想使用lodash库,但我不熟悉。这只是针对您的案例的尝试。可能对您有帮助。@MohammadUsman…如果您改进您的方法,您可能会从一般迭代切换到一般迭代(数据)转换。@WaseemAhmed…如果您阅读了Usman的fiddle方法,请不要将其作为最终答案,因为它不完全符合您的要求。您要求的是一种通用的工作方法-…具有javascript中任何级别的属性?