EN
JavaScript - updating object property?
1 answers
0 points
How can I update object's property in JavaScript?
I have the following object:
xxxxxxxxxx
1
var myObject = {
2
id: 1,
3
theme: {
4
name: 'light',
5
color: '#ffffff',
6
},
7
};
I've tried pushing a new value of theme
property to myObject
like this but it doesn't work:
xxxxxxxxxx
1
myObject.theme.push({ name: 'dark', color: '#000000' });
1 answer
0 points
ES6+ solutions
1. You can create new object by using spread syntax (...
) to copy all the properties from the original object and change only the one you want.
xxxxxxxxxx
1
const myObject = {
2
id: 1,
3
theme: {
4
name: 'light',
5
color: '#ffffff',
6
},
7
};
8
9
const updatedObject = { myObject, theme: { name: 'dark', color: '#000000' } };
10
11
console.log(JSON.stringify(updatedObject, null, 4)); // { id: 1, theme: { name: 'dark', color: '#000000' } }
Note:
This solution creates a copy of the original object.
2. Another solution would be to use Object.assign()
method to modify the existing object.
xxxxxxxxxx
1
const myObject = {
2
id: 1,
3
theme: {
4
name: 'light',
5
color: '#ffffff',
6
},
7
};
8
9
Object.assign(myObject.theme, { name: 'dark', color: '#000000' });
10
11
console.log(JSON.stringify(myObject, null, 4)); // { id: 1, theme: { name: 'dark', color: '#000000' } }
Note:
This solution modifies the original object.
Alternative solution
For older versions of JavaScript, you can use property accesors to update the object's value. In the example below, we use dot property accessor.
xxxxxxxxxx
1
var myObject = {
2
id: 1,
3
theme: {
4
name: 'light',
5
color: '#ffffff',
6
},
7
};
8
9
myObject.theme = {
10
name: 'dark',
11
color: '#000000',
12
};
13
14
console.log(JSON.stringify(myObject, null, 4)); // { id: 1, theme: { name: 'dark', color: '#000000' } }
Note:
This solution modifies the original object.
References
0 commentsShow commentsAdd comment