簡體   English   中英

如何根據數組對象的值和位置嵌套數組對象組?

[英]How to nest groups of array objects based on their values and positions?

我有一個結構如下的數組:

[
  {
    "combinator": "OR"
  },
  {
    "combinator": "AND"
  },
  {
    "combinator": "AND"
  },
  {
    "combinator": "OR"
  },
  {
    "combinator": "AND"
  },
  {
    "combinator": "AND"
  }
]

我需要從中創建另一個數組,該數組會將組合子值為“OR”的所有對象放在頂層,並將兩個“OR”對象之間的所有“AND”對象嵌套到它們之前的“OR”object 中,按順序得到這樣的東西:

[
  {
    "combinator": "OR",
    "subarray": [
      {
        "combinator": "AND"
      },
      {
        "combinator": "AND"
      },
    ]
  },
  {
    "combinator": "OR",
    "subarray": [
      {
        "combinator": "AND"
      },
      {
        "combinator": "AND"
      },
    ]
  },
]

有誰知道如何做到這一點?

以下假設數組中始終有一個前導“OR”,並對后面的那些進行分組,直到遇到新的“OR”並重復

 const grouped = data.reduce((a,c)=>{ if(c.combinator === 'OR'){ a.push({combinator: 'OR', subarray:[]}) }else{ a[a.length-1].subarray.push(c) } return a; },[]); console.log(grouped)
 .as-console-wrapper {max-height: 100%;important:top:0}
 <script> const data=[{combinator:"OR"},{combinator:"AND"},{combinator:"AND"},{combinator:"OR"},{combinator:"AND"},{combinator:"AND"}]; </script>

暫無
暫無

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

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