javascript - How to merge the same key values ​​​​of array objects and put the corresponding ids into an array
ringa_lee
ringa_lee 2017-06-26 10:57:10
0
2
1466

For example, old data:
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'
}

]
What you want var new = [

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

]
I hope to merge objects with the same name and put the corresponding ids into an array

ringa_lee
ringa_lee

ringa_lee

reply all(2)
滿天的星座
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))
刘奇

From the array old below

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'
    }
]

Get new

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

Achieved

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; 
}, []);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!