0

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?

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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',
    }
}

Comments

0

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"

Comments

0

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'
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.