V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Colorful

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

  •  
  •   Colorful · Dec 10, 2019 · 2935 views
    This topic created in 2340 days ago, the information mentioned may be changed or developed.

    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 replies    2019-12-10 12:15:02 +08:00
    shintendo
        1
    shintendo  
       Dec 10, 2019
    lodash.groupBy
    shintendo
        2
    shintendo  
       Dec 10, 2019
    原生的话:[...Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)}))
    shintendo
        3
    shintendo  
       Dec 10, 2019
    少了个 new
    [...new Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)}))
    otakustay
        4
    otakustay  
       Dec 10, 2019
    const groups = groupBy(arr, i => i.c);
    Object.entries(groups).map(([c, child]) => ({c, child}));
    Colorful
        5
    Colorful  
    OP
       Dec 10, 2019
    @shintendo 懂了,涨知识了,感谢厂
    Colorful
        6
    Colorful  
    OP
       Dec 10, 2019
    第一次了解 groupBy 这个语法,太感谢了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1512 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 16:44 · PVG 00:44 · LAX 09:44 · JFK 12:44
    ♥ Do have faith in what you're doing.