簡體   English   中英

如何將一個包含數組的 object 拆分為多個對象

[英]How to split one object with an array in it to multiple objects

我想知道是否可以將 object 拆分為多個對象。 我有一個對象數組,其中包含另一個數組,我想知道是否可以為內部數組中的每個 object 拆分這些對象。 就像是:

obj1 = [{
  a: 1,
  b: [{c: 2},{d: 3}],
  e: 4
}]

obj2 =[
  {
    a: 1,
    b: [{c: 2}],
    e: 4
  },
  {
    a: 1,
    b: [{d: 3}],
    e: 4
  }
]

object始終是這種形式,不管是一個object還是幾百個。 雖然某些對象中可能有更多字段,但只有一個字段帶有數組。 目前,我正在映射原始數組,然后在b數組中再次映射以到達其中的每個 object。 但是,我不知道 go 從那里到哪里,因為從 map 返回的 object 將只是原始數組。 我不知道如何將b陣列和 map 與原始陣列分開。 我想到了 {...orig, b: map()} 但我認為它不適用於每個 object

根據您帖子中的描述,您走在正確的軌道上。 您必須遍歷源 object,並在每次迭代中循環遍歷b數組以提取每個元素,並將其與新 object 中的源迭代元素一起推送到目標數組中。

 var source = [{ a: 1, b: [{ c: 2 }, { d: 3 }], e: 4 }]; // define target as an array var target = []; // loop through source source.forEach((srcElement) => { // loop through `b` array attribute srcElement.b.forEach((bElement) => { // push object into target with source element attributes // and current `b` element wrapped into an array target.push({...srcElement, b: [bElement] }); }); }); console.log(target);

注意:此解決方案假定在您的源 object 的每次迭代中, b屬性存在並且是Array類型。

暫無
暫無

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

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