skip to Main Content

I’m confused to merge array contents from JavaScript.
Please help to get the best way to get desired result. A i also have tried other ways referred on SO.

[
    {
        "Afghanistan": 2646432,
        "categories": "2018"
    },
    {
        "Afghanistan": 6545700,
        "categories": "2019"
    },
    {
        "Afghanistan": 7475886,
        "categories": "2020"
    },
    {
        "Albania": 740232,
        "categories": "2018"
    },
    {
        "Albania": 2374785,
        "categories": "2019"
    },
    {
        "Albania": 2180850,
        "categories": "2020"
    }
]

This was my expected output::

[ { "Afghanistan": 2646432, "Albania": 740232, "categories": "2018" }, { "Afghanistan": 6545700, "Albania": 2374785, "categories": "2019" }, { "Afghanistan": 7475886, "Albania": 2180850, "categories": "2020" } ]

2

Answers


  1. array.reduce((acc, item) => {
        const found = acc.find(obj => obj.categories === item.categories);
        if (found) {
            Object.assign(found, item);
        } else {
            acc.push(item);
        }
        return acc;
    }, [])
    
    Login or Signup to reply.
  2. let list=[{Afghanistan:2646432,categories:"2018"},{Afghanistan:6545700,categories:"2019"},{Afghanistan:7475886,categories:"2020"},{Albania:740232,categories:"2018"},{Albania:2374785,categories:"2019"},{Albania:2180850,categories:"2020"},{India:2029282726,categories:"2022"},{India:2029282729,categories:"2023"},{Afghanistan:2029282729,categories:"2023"}];
    
    let result = Object.values(list.reduce((acc, cur) => (acc[cur.categories] ? acc[cur.categories] = {...acc[cur.categories], ...cur} : acc[cur.categories] = cur, acc), {}));
    
    console.log(result);

    You can use reduce method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search