数组对象相同的key值合并,并且把对应的id放到一个数组

229 阅读1分钟
var old = [

{
    code: 1,
    mlid: 'css',
    type: 'html'
},
{
    code: 2,
    mlid: 'css',
    type: 'html'
},
 {
    code: 3,
    mlid: 'javacript',
    type: 'cod11e'
},
{
    code: 4,
    mlid: 'javacript',
    type: 'cod11e'
}
]
 var hash = {};
var i = 0;
var res = [];
old.forEach(item => {
    var mlid = item.mlid;
    hash[mlid] ? res[hash[mlid] - 1].code.push(item.code) : hash[mlid] = ++i && res.push({
        code: [item.code],
        mlid: mlid,
        type: item.type
    })

});
console.log(JSON.stringify(res))