例如舊資料:
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放到一個陣列
怪我咯2017-06-26 10:59:10
從下面的陣列 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;
}, []);