Home > other >  Combine javascript objects from an array that contain almost similar key
Combine javascript objects from an array that contain almost similar key

Time:01-13

I have an array that contains objects. The array looks like this:

[
    {
        "number": "10a",
        "person": "Velvet"
    },
    {
        "number": "10b",
        "person": "Edna"
    },
    {
        "number": "11a",
        "person": "Shionne"
    },
    {
        "number": "11b",
        "person": "Aifread"
    },

]

I want to combine objects that have identical number property. For example, the first two objects have property number: "10a", and number: "10b". I want these to be combined such that the output becomes:

{
    "10": {
       "person": ["Velvet", "Edna"]
    },
    "11": {
       "person": ["Shionne", "Aifread"]
    }
}

I am not sure how to do it as it seems too complicated for me. I also looked over stackoverflow but can't seem to find a similar problem, hence, my post. Thanks for the help!

CodePudding user response:

I'll assume that the normalization for number is just to remove non numeric characters. If so, you can just iterate over the original array and process each element:

var original = [
    {
        "number": "10a",
        "person": "Velvet"
    },
    {
        "number": "10b",
        "person": "Edna"
    },
    {
        "number": "11a",
        "person": "Shionne"
    },
    {
        "number": "11b",
        "person": "Aifread"
    },
];

const merged = {}
    
        original.forEach(item => {
            var normalizedKey = item.number.replaceAll( /\D/g, "" )
            if(!merged[normalizedKey]) merged[normalizedKey] = { person: []}
            merged[normalizedKey].person.push(item.person)
        })
        
        console.log({merged})
    

CodePudding user response:

Parse number. Add object if missing and append name:

const result = {};
arr.forEach(o => {
    const nr = o.number.slice(0,2);
    result[nr] = result[nr] || {person:[]};
    result[nr].person.push(o.person);
});

console.log(result);
  • Related