JavaScript分组一个包含复杂对象的数组

3

经过多次尝试和搜索,我仍无法解决以下问题:
我有以下数组:

[
{text: "text", title: "title", cid: "cid", active: true, nodes: [
  {title: "subTitle", text: "subText", cid: "cid", active: true, nodes: [
    {text:"123", title:"321"}, 
    {text:"456", title:"654"},
    {text:"789", title:"765"}
  ]},
   {title: "subTitle", text: "subText2", cid: "cid2", active: true, nodes: [
    {text:"testText", title:"testTitle1"}, 
    {text:"testText", title:"testTitle2"},
    {text:"testText", title:"testTitle3"}
  ]},
  {title: "subTitle", text: "subText3", cid: "cid3", active: true, nodes: [
    {text:"ycycy", title:"asd"}, 
    {text:"nyd", title:"yf"},
    {text:"xfg", title:"qq"}
  ]},
  {title: "anotherSubTitle", text: "subText4", cid: "cid4", active: true, nodes: [
    {text:"fff", title:"hhh"}, 
    {text:"xxx", title:"sss"},
    {text:"hhh", title:"jjj"}
  ]}
]}
]

我希望您能达到以下格式:
[
{text: "text", title: "title", cid: "cid", active: true, nodes: [
  {title: "subTitle", text: "subText", cid: "cid", active: true, nodes: [
    {text:"123", title:"321"}, 
    {text:"456", title:"654"},
    {text:"789", title:"765"},
    {text:"testText", title:"testTitle1"},
    {text:"testText", title:"testTitle1"},
    {text:"testText", title:"testTitle1"},
    {text:"ycycy", title:"asd"}, 
    {text:"nyd", title:"yf"},
    {text:"xfg", title:"qq"}
  ]},
  {title: "anotherSubTitle", text: "subText4", cid: "cid4", active: true, nodes: [
    {text:"fff", title:"hhh"}, 
    {text:"xxx", title:"sss"},
    {text:"hhh", title:"jjj"}
  ]}
]}
]

我尝试使用array.reduce和循环遍历数组,但每次都得到错误的结果...
有什么建议吗?


2
你能把你尝试过的reducer包含进来吗? - zcoop98
传统意义上似乎没有任何“分组”操作。只是将第二级元素中nodes数组中的所有元素移动到第一个元素的nodes数组中。 - Heretic Monkey
这个回答解决了你的问题吗?如何使用lodash将对象数组中相同属性的值合并/连接起来? - Heretic Monkey
很遗憾,没有任何答案可以帮助到您...实际上,我正在尝试按第一层节点中的“文本”进行分组。 - Gothiquo
1个回答

4
您可以通过属性对所有级别进行嵌套分组。

const
    groupBy = (array, key) => array.reduce((r, { nodes, ...o }) => {
        let temp = r.find(q => q[key] === o[key]);
        if (!temp) r.push(temp = o);
        if (nodes) (temp.nodes ??= []).push(...groupBy(nodes, key));
        return r;
    }, []),
    data = [{ text: "text", title: "title", cid: "cid", active: true, nodes: [{ title: "subTitle", text: "subText", cid: "cid", active: true, nodes: [{ text: "123", title: "321" }, { text: "456", title: "654" }, { text: "789", title: "765" }] }, { title: "subTitle", text: "subText2", cid: "cid2", active: true, nodes: [{ text: "testText", title: "testTitle1" }, { text: "testText", title: "testTitle2" }, { text: "testText", title: "testTitle3" }] }, { title: "subTitle", text: "subText3", cid: "cid3", active: true, nodes: [{ text: "ycycy", title: "asd" }, { text: "nyd", title: "yf" }, { text: "xfg", title: "qq" }] }] }],
    result = groupBy(data, 'title');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接