克隆对象基于 属性 javascript

Clone object based on property javascript

我正在 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"] 
  }
  ...
]

您可以使用 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);