簡體   English   中英

基於屬性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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM