V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Colorful
V2EX  ›  前端开发

请教一个数组合并方面的问题

  •  
  •   Colorful · 2019-12-10 09:49:26 +08:00 · 2480 次点击
    这是一个创建于 1589 天前的主题,其中的信息可能已经有所发展或是发生改变。

    let arr = [{a:21,b:22,c:5},{a:11,b:21,c:4},{a:31,b:'2a',c:4},{a:'1aaa',b:'2a',c:5}]

    我想合并成

    let arr2 = [{c:4,child:[{a:11,b:21,c:4},{a:31,b:'2a',c:4}]},{c:5,child:[{a:21,b:22,c:5},{a:'1aaa',b:'2a',c:5}]}];

    就是把 C 4 相同的数据,整合到一个数组下面

    6 条回复    2019-12-10 12:15:02 +08:00
    shintendo
        1
    shintendo  
       2019-12-10 10:05:12 +08:00
    lodash.groupBy
    shintendo
        2
    shintendo  
       2019-12-10 10:11:19 +08:00
    原生的话:[...Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)}))
    shintendo
        3
    shintendo  
       2019-12-10 10:12:21 +08:00
    少了个 new
    [...new Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)}))
    otakustay
        4
    otakustay  
       2019-12-10 11:12:48 +08:00
    const groups = groupBy(arr, i => i.c);
    Object.entries(groups).map(([c, child]) => ({c, child}));
    Colorful
        5
    Colorful  
    OP
       2019-12-10 12:14:35 +08:00
    @shintendo 懂了,涨知识了,感谢厂
    Colorful
        6
    Colorful  
    OP
       2019-12-10 12:15:02 +08:00
    第一次了解 groupBy 这个语法,太感谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3479 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:52 · PVG 19:52 · LAX 04:52 · JFK 07:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.