Home > database >  Update a nested object in JavaScript
Update a nested object in JavaScript

Time:01-23

This is the original data

const data = {
    "field1": {
        "name": 'Anuv',
        "marks": {
            "eng": 43,
            "hindi": 23
        },
        "age": 21
    },
    "field2": {
        "school": 'DAV'
    }
}

I am trying to update the name

const updatedValue = {
    "field1": {
        "name": "Anuv Gupta"
    }
}

This is the expected data. It should have all the field and the updated name value as well.

const expectedData = {
    "field1": {
        "name": 'Anuv Gupta',
        "marks": {
            "eng": 43,
            "hindi": 23
        },
        "age": 21
    },
    "field2": {
        "school": 'DAV'
    }
}

I have tried using these

expectedData = Object.assign({}, data, updatedValue) 

as well as

expectedData =  { ...data, ...updatedValue },

both of them returns this object

const obj = {
        "field1": {
            "name": 'Anuv Gupta',
        },
        "field2": {
            "school": 'DAV'
        }
    }

How do I fix this and get the expectedData object?

CodePudding user response:

Avi's answer is good. Just to add one more method that is strictly immutable, you could do the following:

const expectedData = {
    ...data,
    "field1": {
        ...data.field1,
        "name": 'Anuv Gupta',
    }
}

CodePudding user response:

If you don't care about mutating your original data you can just do:

data.field1.name = 'Anuv Gupta';
console.log(data);

If you don't want your original data to mutate, just clone it first and do the new value assignment:

const dataClone = structuredClone(data);
dataClone.field1.name = 'Anuv Gupta';
console.log(dataClone);

Edit:

Like others suggested you can also achieve that by spreading your data object into a new one like so:

const newData = {
  ...data,
  field1: {
    ...data.field1,
    name: 'Anuv Gupta',
  }
}

It works but it is not mutation proof as it only shallow clones the original data object - You can read more about shallow vs deep clone in this great blog post. if you care about not mutating your original data, I would use the second option I mentioned in my answer

CodePudding user response:

You can access the name property directly:

data.field1.name = "new value"

If you're trying to avoid mutating the original data obj you can try:

data2 = Object.assign({}, data);
data2.field1.name = "new value"

CodePudding user response:

just change it directly using an Object property

data.field1.name = 'anuv Gupta'

and don't use quotes for object keys just do this and it works just fine

const obj = {
        field1: {
            name: 'Anuv Gupta',
        },
        field2: {
            "school": 'DAV'
        }
    }
  • Related