Hey,
I’m trying to access an object within an array within an object, from another property within the object. What am I doing wrong? Here’s the codepen.
Thanks!
Hey,
I’m trying to access an object within an array within an object, from another property within the object. What am I doing wrong? Here’s the codepen.
Thanks!
In your case, this
is referring to the global window, not the object.
Thanks! I didn’t think about that. Do you know how I can fix that?
I’d suggest looking into a class
.
Ok, thanks! I’ll try that
The code does not work because this
keyword inside the object literal definition does not refer to the object itself (myObj
), but to the global object (window
in a browser or global
in Node.js) when the object is been creating.
To access this we can write your code this way
const myObj = {
objArr: [{ name: 'item1', color: 'red', }],
info: function () { return `${this.objArr[0].name}` }
};
const p = document.querySelector('p');
p.textContent = myObj.info();
or this way if you don’t to use the this keyword
const myObj = {
objArr: [{ name: 'item1', color: 'red', }],
};
myObj.info = `${myObj.objArr[0].name}`;
const p = document.querySelector('p');
p.textContent = myObj.info;
Those work great! Thanks for the help!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.