克隆对象基于属性javascript

时间:2017-05-30 13:19:38

标签: javascript arrays grouping clone

我正在使用JSON中的一组对象

[ 
    { name: "Doc 1", 
      product: ["product 1", "product 2"],
      type: ["type 1", "type 2"] 
    },
    { name: "Doc 2", 
      product: ["product 1"],
      type: ["type 1"] 
    },
    { name: "Doc 3", 
      product: ["product 2"],
      type: ["type 2"] 
    }
    ...
]

我需要先为对象的每个产品克隆对象(所以我有2个Doc 1实例)然后我想根据产品对对象进行分组(这会给我另外2个对象)然后根据给我另外2的类型进行分组。

最初我们只是根据产品进行分组,但后来发现我们的文档中有多个与之相关的产品,所以我们需要对原始产品进行转换。

如何将每张卡克隆到每个产品的新阵列?

预计最后一组对象看起来就像这个简单的实例,Doc 1是唯一的副本,因为它与产品1和2相关联。

[ 
  { name: "Doc 1", 
    product: ["product 1", "product 2"],
    type: ["type 1", "type 2"] 
  },
  { name: "Doc 1", 
    product: ["product 1", "product 2"],
    type: ["type 1", "type 2"] 
  },
  { name: "Doc 2", 
    product: ["product 1"],
    type: ["type 1"] 
  },
  { name: "Doc 3", 
    product: ["product 2"],
    type: ["type 2"] 
  }
  ...
]

1 个答案:

答案 0 :(得分:1)

您可以使用Object.assign克隆对象,使用[].concat(yourArray)克隆基元数组。

var docs = [ 
    { name: "Doc 1", 
      product: ["product 1", "product 2"],
      type: ["type 1", "type 2"] 
    },
    { name: "Doc 2", 
      product: ["product 1"],
      type: ["type 1"] 
    },
    { name: "Doc 3", 
      product: ["product 2"],
      type: ["type 2"] 
    }
]

var cloned = docs.map(function (c) {
   // This will not clone the product
   c = Object.assign({}, c);
   
   // Clone the product array
   c.product = [].concat(c.product);
   return c;
});

// Group by products
var byProduct = {
  /*
    "product 1": [...]
  */
};

cloned.forEach(function (c) {
  c.product.forEach(function (prod) {
    var groupedDocs = byProduct[prod] = byProduct[prod] || [];
    groupedDocs.push(c);
  });
});

console.log(byProduct);