Handling JSON Object Array
I got a realy simple question:
Take a look at this JSON String:
this.objects = [{"pid":"2","x":"10","y":"10"}]; // only one i know
Now i would like to adress an object out of it like so:
this.objects.pid[2]
I know thats pointless in this case as you would access it like:
this.objects[0]
The thing is that i need to adress an object array in JSON by the object id and not the arr开发者_如何学运维ay index. Is there a nice approach to this?
Thanks!
function getObject(id, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].pid == id) {
return array[i]
}
}
}
A function that takes your id and array and returns your object. Basically loop through the array and find the element with your id. This can be optionally cached for speed increase.
It doesn't need to be a single element array, so try this...
this.objects = {"pid":"2", "x":"10", "y":"10"};
And you can read it either of these ways:
this.objects.pid;
this.objects['pid'];
If you wanted multiple lists of x,y,etc. then try something like this:
this.objects = { "2": {"x": "10", "y": "10"} };
this.objects["2"].x;
this.objects["2"]["x"];
Essentially, in this case, just use the "pid" as they key for each object that contains the properties you want for each item.
精彩评论