84669 人が学習中
152542 人が学習中
20005 人が学習中
5487 人が学習中
7821 人が学習中
359900 人が学習中
3350 人が学習中
180660 人が学習中
48569 人が学習中
18603 人が学習中
40936 人が学習中
1549 人が学習中
1183 人が学習中
32909 人が学習中
例: 古いデータ: var old = [
]あなたが望むもの var new = [
]同じ名前のオブジェクトをマージし、対応する ID を配列に入れたいと考えています
ringa_lee
var hash = {}; var i = 0; var res = []; old.forEach(function(item) { var name = item.name; hash[name] ? res[hash[name] - 1].id.push(item.id) : hash[name] = ++i && res.push({ id: [item.id], name: name, type: item.type }) }); console.log(JSON.stringify(res))
从下面的数组 old 里
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
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; }, []);
从下面的数组
old
里得到
new
实现