+ 1
How to access dynamic nested objects in JavaScript?
Hi! Beginner here. I've been trying to figure out how I could do this. Below is some of the code: var items = { list: [], startList: function (text){ this.list.push({text:text, array:[]}) }, addToList: function (text){ this.list.push({text:text, array:[]}) } } The text value would be added dynamically. The startList part is alright. It's the addToList part I have a problem with. I want it to be able to add to arrays within the list array. But how do I reference what has not even been created yet?
4 Antworten
+ 1
You forgot a couple ending curly brackets, I've marked them for you. Here's the right code:
var items = {
list: [],
startList: function (text) {
this.list.push({text:text, array:[]})
},// ^
addToList: function (text) {
this.list.push({text:text, array:[]})
}// ^
}
Hope this helped :)
+ 1
Thanks @Just A Rather Ridiculously Long Username (to type). I've corrected the errors. Unfortunately that isn't the problem though.
0
Oh okay, I was not entirely sure what you meant by "how do I reference what has not even been created yet?". What exactly are you trying to reference, and why would you want to reference what has not even been created yet?
If you meant you wanted to reference the 'array' property of the first object inside 'list', here's how you would do it:
this.list[0].array.push(whatever);
If you simply want to "add to arrays within the list array", then:
this.list.push([]);
If you could specify exactly where the problem is, I may be able to help you out.
0
Hey, thanks! I think I got it now...at least some of it. Please bear with me.
This is at the very least near what it should look like:
var items = {
list: [],
startList: function (text){
this.list.push({text:text, array:[]})
},
addToList: function (position, text){
this.list[position].push({text:text, array:[]})
}
}
console.log (items.startList ("first"))
would result in an object with the text "first" and an empty array.
console.log (items.addToList (0, "second"))
would result in an object with the text "second" and an empty array inside the initial array with the text "first". That's all great.
The challenge now is what to do when I want to further nest another array inside the object with the text "second" like I did with the first. I've tried all I could but nothing's worked. Thanks for your patience Ridiculously Long Username!