Home > other >  how to chnage values of object coming in nested array
how to chnage values of object coming in nested array

Time:07-13

Im trying to chnage the object values in map loop on nested array

Object Examples

var data = [[{name: 'test', values: [{isSelected: true}] }]]



 var resertData = data.map(filterArray => {
    return filterArray.map(filter => {
        return filter.values.map(values => {
            return values.isSelected = false
        })
    })
})

required output should be

[[{name: 'test', values: [{isSelected: false}] }]]

and Im getting with my code

'[[[false]]]'

Please help me guys

Thanks in advance :)

CodePudding user response:

Well clearly returning just the changed fields overwrites existing ones. Return entire objects specifying values of fields you want to change, and use object destructuring to preserve existing ones. Try this:

    var resertData = data.map(filterArray => {
    return filterArray.map(filter => {
        return {
            ...filter,
            values : filter.values.map(values => {
                return {isSelected : false}
            })

        }
    })
})

CodePudding user response:

To update the property value in the original object. You can use Array.forEach()

Live Demo :

var data = [[{name: 'test', values: [{isSelected: true}] }]];

data.forEach(filterArray => {
    filterArray.forEach(filter => {
        filter.values.forEach(values => {
            values.isSelected = false
        });
    });
});

console.log(data);

Or you can achieve this via more cleaner way :

var data = [[{name: 'test', values: [{isSelected: true}] }]];

const [[dataObj]] = data;

dataObj.values.forEach(o => o.isSelected = false);

console.log(data);

  • Related