javascript - 如何把数组对象相同的key值合并,并且把对应的id放到一个数组
ringa_lee
ringa_lee 2017-06-26 10:57:10
0
2
1425

例如旧数据:
var old = [

{ id: 1, name: 'css', type: 'html' }, { id: 2, name: 'css', type: 'html' }, { id: 3, name: 'javacript', type: 'code' }, { id: 4, name: 'javacript', type: 'code' }

]
想得到的 var new = [

{ id: [1,2], name: 'css', type: 'html' }, { id: [3,4], name: 'javacript', type: 'code' },

]
希望把相同name的对象合并,并且把对应的id放到一个数组

ringa_lee
ringa_lee

ringa_lee

全部回复 (2)
滿天的星座

雷雷

    刘奇

    从下面的数组old

    var old = [ { id: 1, name: 'css', type: 'html' }, { id: 2, name: 'css', type: 'html' }, { id: 3, name: 'javacript', type: 'code' }, { id: 4, name: 'javacript', type: 'code' } ]

    得到new

    var new = [ { id: [1,2], name: 'css', type: 'html' }, { id: [3,4], name: 'javacript', type: 'code' } ]

    实现

    var isEqual = (a, b) => a.name === b.name && b.type === b.type; var create = e => { e.id = [e.id]; return e; } var getNew = old => old.reduce((acc, cur) => { let hasItem = acc.some(e => { let temp = isEqual(e, cur); if (temp) e.id.push(cur.id); return temp; }); if (!hasItem) acc.push(create(cur)) return acc; }, []);
      最新下载
      更多>
      网站特效
      网站源码
      网站素材
      前端模板
      关于我们 免责声明 Sitemap
      PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!