0

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?

2
  • 2
    obj.link = {link: 'test'} Commented Feb 15, 2022 at 13:02
  • Best one I think, can you make an answer so I can accept it please? Commented Feb 15, 2022 at 17:47

2 Answers 2

1

You're trying to access link property inside link, which is not there by the time. So you can do below things.

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

Or

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.