skip to Main Content

i have this array of object as follows

let data = [
    { "id": "12", "values": [ "_status.com", "_verify.com" ] },
    { "id": "12", "values": [ "_result.com"] },
    { "id": "15", "values": [ "_integrate.com"] }
]

If you notice, array of object has 2 objects with the same id 12 and it has 3 variables in values combined together. Similarly id 15 has only one values variable.

How do i group them together and accumulate the values property in one array. I want to achieve below result.

let result = [
    { "id": "12", "values": [ "_status.com", "_verify.com", "_result.com" ] },
    { "id": "15", "values": [ "_integrate.com"] }
]

can someone let me know how to achieve this. i did search online regarding iteration of array of objects but this is a very unique and different example and i could not find anything close to solving it.

2

Answers


  1. Using reduce by iterating through the data array.
    For each object in the array, check if an entry for the id already exists in the accumulator object (acc):

    • If not, create a new entry with an empty values array.
    • If yes, concatenate the values array of the current object to the existing values array in the accumulator.

    Finally use Object.values() to extract the accumulated values as an array and assign it to the result variable

    let data = [
        { "id": "12", "values": [ "_status.com", "_verify.com" ] },
        { "id": "12", "values": [ "_result.com"] },
        { "id": "15", "values": [ "_integrate.com"] }
    ];
    
    let result = Object.values(data.reduce((acc, {id, values}) => {
        if (!acc[id]) {
            acc[id] = { id, values: [] };
        }
        acc[id].values = acc[id].values.concat(values);
        return acc;
    }, {}));
    
    console.log(result);
    Login or Signup to reply.
  2. You could also Object.groupBy the id‘s and then map() the objects to combine the values

    let data = [
        { "id": "12", "values": [ "_status.com", "_verify.com" ] },
        { "id": "12", "values": [ "_result.com"] },
        { "id": "15", "values": [ "_integrate.com"] }
    ]
    
    const grouped = Object.groupBy(data, s => s.id);
    const combined = Object.keys(grouped).map(id => (
        { id, values: grouped[id].flatMap(f => f.values) }
    ));
    
    console.log(combined);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search