Home > front end >  Push value to multiple arrays
Push value to multiple arrays

Time:01-27

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?

CodePudding user response:

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.

  • Related