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

JavaScript add arrays to existing array of objects

I’ve below code snippet

const arr = [
    {
        "name": "Attestation Component 1",
        "values": [
            {
                "component": "Attestation Component 1"
            },
            {
                "component": "Attestation Component 1"
            },
            {
                "component": "Attestation Component 1",
            }
        ]
    },
    {
        "name": "Attestation Component 2",
        "values": [
            {
                "id": "10005884",
                "url": "https://www.msn.com",
                "bfaId": "G44.5.3.1N/A",
                "component": "Attestation Component 2"
            },
            {
                "id": "10005883",
                "url": "https://www.hotmail.com",
                "bfaId": "G44.5.3.2N/A",
                "component": "Attestation Component 2"
            }
        ]
    },
    {
        "name": "Attestation Component 3",
        "values": [
            {
                "id": "10005882",
                "url": "https://www.rediffmail.com",
                "bfaId": "G44.5.3.3N/A",
                "component": "Attestation Component 3"
            }
        ]
    }
]

const bool = arr.map(group => group.values.every(val => val.id));
console.log(bool);

I’ve three object with name Attestation Component 1, Attestation Component 2 ,Attestation Component 3. I’m getting the expected output as false, true, true. What’s the reason for this? I want to add the property to the existing array of object as something isInvalid: true/false below name

Expected O/P (add property in each object with below key value pairs)
isInvalid: true/false

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 :

That is because your algorithm is incorrect. The every method will check if all the objects have an id, but that is not what you want right ?

So try this instead

const bool = arr.map(group => group.values.some(val => val.id)).filter(bool => !bool).toString();
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