合并具有相同键值的数组中的对象

时间:2020-11-12 05:56:21

标签: javascript arrays json

我有一个看起来像这样的数组:

var arr = [
    {id: 1, tech_id:11, action: 'swim'},
    {id: 2, tech_id:11, action: 'run'},
    {id: 3, tech_id:22, action: 'climb'},
    {id: 4, tech_id:22, action: 'swim'},
    {id: 5, tech_id:11, action: 'jump'},
]

如何使其看起来像这样:

[
    {tech_id: 11, data: [{id: 1, action:'swim'}, {id: 2, action:'run'}, {id: 5, action:'jump'}] }
    {tech_id: 22, data: [{id: 3, action:'climb'}, {id:4, action:'swim'}]}

]

3 个答案:

答案 0 :(得分:1)

您可以将reduceObject.keys一起使用。

var arr = [
    {id: 1, tech_id:11, action: 'swim'},
    {id: 2, tech_id:11, action: 'run'},
    {id: 3, tech_id:22, action: 'climb'},
    {id: 4, tech_id:22, action: 'swim'},
    {id: 5, tech_id:11, action: 'jump'},
]

let mergeObj = arr.reduce((p, c) => {
    const {tech_id, ...otherData} = c;

    if (!(tech_id in p)) {
        p[tech_id] = {
            data: []
        }
    }
    
    p[tech_id].data.push(otherData)
    return p
}, {})

mergeObj = Object.keys(mergeObj).map(key => {
    return {
        tech_id: key,
        data: mergeObj[key].data
    }
})

console.log(mergeObj);

答案 1 :(得分:0)

您可以使用Array reduce和Object Value函数来完成它。

var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]
const result = Object.values(arr.reduce((item, next) => {
if (!item[next.tech_id]) {
    item[next.tech_id] = {
        tech_id: next.tech_id,
        data: []
    };
}

item[next.tech_id].data.push(next);
return item;
}, {}));

console.log(result);

答案 2 :(得分:0)

一个建议是使用Map,其中Map中的每个键都是一个tech_id,每个值都是一个对象数组(不包括tech_id)其中有tech_id。然后,您可以使用Array.from将Map转换为数组,并具有附加的映射功能,以将地图中的每个[key, value]对条目转换为对象([tech_id, data]) => ({tech_id, data})

const arr = [ {id: 1, tech_id:11, action: 'swim'}, {id: 2, tech_id:11, action: 'run'}, {id: 3, tech_id:22, action: 'climb'}, {id: 4, tech_id:22, action: 'swim'}, {id: 5, tech_id:11, action: 'jump'}, ];
const res = Array.from(arr.reduce((map, {tech_id,  ...r}) => 
  map.set(tech_id, [...(map.get(tech_id) || []), r])
, new Map), ([tech_id, data]) => ({tech_id, data}));

console.log(res);
.as-console-wrapper { max-height: 100% !important;} /* ignore */