Let’s say for example, I have the following Javascript object:
var Object = {
Person_A: { name: 'James', age: 40, country: 'Spain' },
Person_B : { name: 'Smith', age: 50, country: 'France' }
}
I want to know how many properties there are in the object Object, and access these properties numerically e.g. through Object[n].
Until now (I don’t use Javascript objects much, but I do use JSON as a return format when working with AJAX) I didn’t know that Javascript objects don’t have a length method and can’t be accessed numerically.
I’ve tried to convert the Javascript object into the same type of JSON that is returned when I make AJAX calls (the JSON is returned as an object with a length method, and is numerically accessible – just read another thread, and maybe I’m wrong about this – double checking now) using JSON.parse(JSON.stringify(Object)) but that simply returns the same exact Object.
So, my question is, what’s the most efficient way to take an object like the example, and make it accessible numerically and have a length method.
Any help would be greatly appreciated (and please ask if you need any clarification of my question).
Thanks.
Given an object, this will add the numeric indices to that object. So after running it through that function, the object will have both string keys and numeric keys. If you have the optional line too, you automatically get a
lengthproperty as well.