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

Push value to multiple arrays

const array = [{
    id: 1,
    name: 'test',
    attrs: [{
        name: 'Attribute 1',
        description: 'Description 1',
    }],
    values: [{
        name: 'value 1',
        attrs: [{
                name: 'Attribute 1',
                type: 'Type 1',
            },
            {
                name: 'Attribute 2',
                type: 'Type 2',
            },
        ],
    }, ],
}, ];

const newArray =
    array.map((item) => {
        return {
            ...item,
            isNegative: true
        };
    });

console.log(newArray);

I receive data as displayed in the const array. I need to push a value ‘isNegative’ to array[].attrs and to each values.attrs. I’m only able to do it to the array[].attrs. How can I do it to the others?

>Solution :

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

You’re only mapping over the top-level array. If you need to map over the arrays within each object, that’s another call to .map(). For example:

const array = [{
    id: 1,
    name: 'test',
    attrs: [{
        name: 'Attribute 1',
        description: 'Description 1',
    }],
    values: [{
        name: 'value 1',
        attrs: [{
                name: 'Attribute 1',
                type: 'Type 1',
            },
            {
                name: 'Attribute 2',
                type: 'Type 2',
            },
        ],
    }, ],
}, ];

const newArray =
    array.map((item) => {
        return {
            ...item,
            isNegative: true,
            attrs: item.attrs.map((attr) => {
                return {
                    ...attr,
                    isNegative: true
                }
            })
        };
    });

console.log(newArray);

Same with the values property, any array within objects in values, etc. Any array that you want to map to a new structure, call .map() on it.

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