简体   繁体   English

如何根据数组对象的值和位置嵌套数组对象组?

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

I have an array that's structured like this:我有一个结构如下的数组:

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

I need to create another array from it that would place all the objects with combinator value of "OR at the top level, and nest all the "AND objects between two "OR" objects into an "OR" object that precedes them, in order to get something like this:我需要从中创建另一个数组,该数组会将组合子值为“OR”的所有对象放在顶层,并将两个“OR”对象之间的所有“AND”对象嵌套到它们之前的“OR”object 中,按顺序得到这样的东西:

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

Does anyone know how can this be done?有谁知道如何做到这一点?

Following assumes there is always a leading "OR" in the array and groups those that follow until a new "OR" is encountered and repeats以下假设数组中始终有一个前导“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.

相关问题 如何从数组中嵌套具有重复值的对象 - How can I nest objects from an array that have repeating values 如何根据值在组中呈现对象项 - How do I render objects items in groups based on values 如何将对象数组转换为位置改变的数组 - How to convert array of objects into array with changed positions 如何根据对象数组中的值过滤键 - how to filter keys based on values in a array of objects 如何使用JQuery / JavaScript将对象数组中的值分组并从这些组中创建新的对象数组 - Using JQuery/JavaScript how would I group values in an array of objects and create a new array of objects from the groups 如何将对象与某些值的位置不相同的对象数组进行比较 - How to compare an object against an array of objects where positions of some values won't be the same 基于数组中不同位置的相同键合并对象 - Merge objects based on same key from different positions in an array 如何嵌套基于数组的异步函数? - How to nest asynchronous functions based on array? 如何根据嵌套数组中的值过滤带有对象的数组并对其进行计数 - How to filter array with objects based on values in nested array and counting them 如何根据对象数组的值创建一个新的项目数组? - How to create a new array of items based on the values of an array of objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM