删除重复的键名并将重复的键相关信息分组到数组中

时间:2019-12-23 12:56:06

标签: javascript

const articles = [{ key : '12', 'desc': {'_id': 'descA'}}, {key: '12', 'desc': 

    {'_id': 'descB'}}, {key: '12', 'desc': {'_id': 'descC'}}, {key: '13', 'desc': {'_id': 'descA'}}, {'key': '13', 'desc': {'_id': 'descAB'}}, {key: '13', desc: {_id: 'descAC'}}
    ];



    let result =  [{key: '12', desc:['descA', 'descB', 'descC']}, {key: '13', desc:['descA','descAB', 'descAC']}];

1 个答案:

答案 0 :(得分:0)


// if duplicate _id's are allowed for the desc key
const result = [...new Set(articles.map(v => v.key))].map((val => ({key: val, desc: articles.filter(v => v.key === val).map(x => x.desc._id)})));
console.log(result);
// if only unique _id's are allowed
const result1 = [...new Set(articles.map(v => v.key))].map((val => ({key: val, desc: [...new Set(articles.filter(v => v.key === val).map(x => x.desc._id))]})));
console.log(result1);