'How to create a new nested property in an object?

If I create an object by doing let obj = {}, I can create a new link property by doing obj.link = 'test' and it works.

What if I want instead to create a nested property?

The code below gives an undefined error:

let obj = {}
obj.link.link = 'test'
console.log(obj.link.link)

What's the right way to do this?



Solution 1:[1]

You need to have an object to address a property inside of an object.

Toassign use a default object and assign with the value to the last property.

let obj = {};

(obj.link ??= {}).link = 'test';

console.log(obj.link.link);
console.log(obj);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1