繁体   English   中英

使用javascirpt对单个数组的多个属性进行分组

[英]Group by with multiple properties on single array using javascirpt

我有要在其上应用两个字段的groupBy()的对象数组。 我可以通过单个字段来实现分组,但是不能通过2个字段来实现。

我想要以以下格式输出:

{
   data: [
     {
        "name":"que1",
         "image":"img1",
        "data":[
            {
               "name":"que1",
               "title":"title1",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title2",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title3",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
           {
               "name":"que1",
               "title":"title4",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            }
           ]
     },
    {
       "name":"que1",
         "image":"img1",
        "data":[
            {
               "name":"que1",
               "title":"title1",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title2",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            }
          ]
    }
  ]
}

_.chain(quesList)
        .groupBy("category","image")
        .map((value, key) => ({ name: key, data: value }))
        .value()

是否有可能实现这种输出? 请帮帮我..

尝试将它们串联以用作分组的虚拟键,因为您可以将回调用作分组算法,因此只需串联并返回它即可。

不要直截了当地连接它,这可能会产生歧义问题。 (例如: "AB" + "C""A" + "BC"的结果相同)使用任何分隔符并将其连接。

只需修改您的ans:

_.chain(quesList)
        .groupBy(({category,image}) => category + '|' + image)
        .map((value) => ({ name: value[0].name, image: value[0].image, data: value }))
        .value()

每个组桅杆都有一些值(由于group by的结果,否则它将不组成组),因此您可以盲目地从第一个对象获取属性。

注意:正确的属性名称要映射到外部,就像我刚才猜测的那样,放置nameimage

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM