Well, I’m so confused. I have made a json element like this:
var world = {"county": []};
world.county.push({name: "America", flag: "yes", countries: []});
world.county[0].countries.push({name: "Costa Rica", capital: "San Jose"});
This leads me to think two things:
- I’m mixing arrays with json objects. How can I avoid using arrays in this scenario?
- How can I add elements to the json root dynamically?
Regarding question 2, I’m facing issues because I don’t know how to add elements to the root, let’s say that I have tried this, but it doesn’t work:
var index = 0;
var word = {};
world.index.push({name: WA});
So, by this way I could add elements iterating some array created previously.
Start with Kolink’s answer. Then, for what you are doing here:
It looks like you are trying to add a property to
worldwith the index 0. Given you are then trying to use.push()it would seem you want that property to be an array, in which case you would do that like this:Given that
worldstarted as an empty object that would create this structure:In a general sense, to access an object property where the property is in a variable you use the
[]array-style syntax. So: