[英]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.