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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.