Home > Net >  How to reassign values in a js object based on the values present in an object within the same objec
How to reassign values in a js object based on the values present in an object within the same objec

Time:10-07

I have an array of objects in the following form-

let result = [
    {
        a: 1,
        b: 2,
        c: 3,
        newValues: {
            a: 10,
            b: 20,
            c: 30
        }
    },
    {
        d: 4,
        e: 5,
        f: 6,
        newValues: {
            d: 40,
            e: 50,
            f: 60
        }
    }
]

And want to convert it to following format -

let result = [
    {
        a: 10,
        b: 20,
        c: 30,
    },
    {
        d: 40,
        e: 50,
        f: 60
    }
]

But have been unable to do so. Any help for converting the older array to the new one will be very much appreciated.

CodePudding user response:

A simple map will do it

let result = [
    {
        a: 1,
        b: 2,
        c: 3,
        newValues: {
            a: 10,
            b: 20,
            c: 30
        }
    },
    {
        d: 4,
        e: 5,
        f: 6,
        newValues: {
            d: 40,
            e: 50,
            f: 60
        }
    }
]

let data = result.map( r => r.newValues)
console.log(data)

CodePudding user response:

The problem by mapping only the r.newValues is you can potentially lost data that never changed and are not in newValues.

const result = [
        {
            a: 1,
            b: 2,
            c: 3,
            newValues: {
                a: 10,
                b: 20,
                c: 30
            }
        },
        {
            d: 4,
            e: 5,
            f: 6,
            newValues: {
                d: 40,
                e: 50
            }
        }
    ];

    const updates = result.map(element => {
       const {newValues, rest} = element;
       delete element.newValues;
       
       return {...element, ...newValues};
    });
    console.log(updates);

It will work even if a value of newValues was not present into newValues.

  • Related