Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine javascript objects from an array that contain almost similar key

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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})
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading