Asking
Asking

Reputation: 4172

Change a value from a nested object using localstorage

I have this code that set the obj value in localstorage.

const obj = {
  name: "Bill",
  meta: {
    age: 18
  }
};
const data = localStorage.setItem('user', JSON.stringify(obj));

Now i want to change the age key in the localstorage: localStorage.setItem('user', JSON.stringify({ ...data, ...data.meta.age= 15 } }));, but it does not work.
How to change the value above and to see the changes in localstorage?

Upvotes: 0

Views: 1096

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074048

Assuming you have data, the problem is that ...data.meta.age = 15 is a syntax error. You don't use = in object literals, and it does't make sense to try to spread the age property (which is a number). Instead:

const newData = {
    ...data,
    meta: {
        ...data.meta,
        age: 15,
    },
};
localStorage.setItem("user", JSON.stringify(newData));

Notice how we have to create a new outermost object and also a new object for meta.

Live Example:

const data = {
    name: "Bill",
    meta: {
        occupation: "Programmer", // Added so we see it get copied
        age: 18,
    },
};
const newData = {
    ...data,
    meta: {
        ...data.meta,
        age: 15,
    },
};
console.log(newData);

Upvotes: 1

Related Questions