Get a JSONObject of a JSONArray with Value by jQuery
Hi assume that I have a JSON like this:
var myJson = [{"id":"111","name":"aaa","surname":"bbb"},
{"id":"222","name":"ccc","surname":"ddd"}]
is there any function to get one of jsonobject with a value of jsonobject开发者_如何学Go? I mean maybe I know that id is 111 how can get the jsonobject with id=111, I don't want to get it with loop I mean is there just function to do it with jQuery?
Change your Json array as below
var myJson = { "idarray":["111","222"],
"dataarray":{ "111":{"name":"aaa","surname":"bbb"},"222":{"name":"ccc","surname":"ddd"}}
};
Now you can access it as below:
myJson.dataarray[myJson.idarray[0]].name // ==> "aaa"
or directly by
myJson.dataarray[111].name // ==> "aaa"
You have an array with two objects in it. To find which array element (if any) has an object with id=="111", you would have to search the array and look at each object to find which one has the desired object in it.
When using a plain array, there is no magic way to find something in it without looping through the array. If keys are unique and order is not important, you can use an object instead of an array to directly index into a given object without searching for it. But given the data structure you or some piece of code has to loop through the array.
function findId(target, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].id == target) {
return(i);
}
}
return(-1);
}
精彩评论