Here’s a quick and more readable way to initialize objects from other variables.
But, first - how do you normally define objects?
I mean.. initialize objects - from other variables.
1
2
3
4
5
|
let x = 2;
let y = 4;
const nums = { x: x, y: y };
console.log(nums);
// { x: 2, y: 4 }
|
You can do the same without using named variables if you like.
1
2
3
4
5
|
let x = 2,
y = 4;
const nums = { x, y };
console.log(nums);
// { x: 2, y: 4 }
|
The same holds true for more complex objects as well.
1
2
3
4
5
6
7
8
9
10
11
|
const earth = { position: 3, life: true };
const mercury = { position: 1, life: false };
const planets = { earth, mercury };
console.log(planets);
/* output
{ earth: { position: 3, life: true },
mercury: { position: 1, life: false }
}
*/
|