search

Home  >  Q&A  >  body text

javascript - How to merge objects with the same key value in an array and put different values ​​into an array after merging

Initially
var old = [

{
    id: 1,
    name: "first"
},
{
    id: 2,
    name: "first"
},
{
    id: 3,
    name: "second"
},
{
    id: 4,
    name: "second"
}

]
The desired result
var new = [

{
    a: [1, 2],
    b: "first"
},
{
    a: [3, 4],
    b: "second"
}

]

伊谢尔伦伊谢尔伦2807 days ago731

reply all(2)I'll reply

  • 学习ing

    学习ing2017-06-26 10:59:14

    For reference

    var new = Array.from(
      old.reduce((dict, item)=> {
        if (dict.has(item.name)) {
          dict.get(item.name).push(item.id)
        } else {
          dict.set(item.name, [item.id])
        }
        return dict
      }, new Map())
    ).map(item => ({a: item[1], b: item[0]}))

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-26 10:59:14

    The original array is

    var old = [
        {
            id: 1,
            name: "first"
        },
        {
            id: 2,
            name: "first"
        },
        {
            id: 3,
            name: "second"
        },
        {
            id: 4,
            name: "second"
        }
    ]

    Expect to get

    new = [
        {
            a: [1, 2],
            b: "first"
        },
        {
            a: [3, 4],
            b: "second"
        }
    ]

    Achieved

    var getNew = old => {
        let temp = old.reduce((acc, cur) => {
            if (acc[cur.name]){
                acc[cur.name].push(cur.id); 
            } else {
                acc[cur.name] = [cur.id]
            }
            return acc; 
        }, {});
        
        return Object.keys(temp).map(key => {
            return {
                a: temp[key],
                b: key
            }
        })
    }

    Just Run getNew(old)

    reply
    0
  • Cancelreply