Search code examples
javascriptarraystypescriptobject

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


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));