I have a json string which is resulted by an ajax call which looks like this
[ {
"name":"sourabh",
"userid":"soruabh开发者_如何转开发bajaj",
"id":"11",
"has_profile_image":"0" },
{
"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0"
}]
The page on my web app uses "id" value as the identification of an object. So I want to display the name of the user where ever users' name is required. What is the fastest way of getting the right user object to output the name or other values of user using the id value. Thanks in advance.
Ok... this answer provides for a lot of overhead at the start, but then makes it faster to reference by id later. It basically makes an array that has each item at the same index of its id. Like I said, a lot of overhead at first but little for later processing
var data = [{"name":"sourabh",
"userid":"soruabhbajaj",
"id":"11",
"has_profile_image":"0" },
{"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0" },
{"name":"sourabh",
"userid":"sourabhbajaj",
"id":"27",
"has_profile_image":"0" },
{"name":"sourabh",
"userid":"sourabhbajaj",
"id":"3",
"has_profile_image":"0" },
{"name":"myname",
"userid":"myuserid",
"id":"5",
"has_profile_image":"0" },
{"name":"sourabh",
"userid":"sourabhbajaj",
"id":"2",
"has_profile_image":"0" }]
arr = [];
data.sort(function(a,b){return Number(a.id) - Number(b.id);})
var k = 0;
var offset = Number(data[0].id);
for(var i = offset; i <= Number(data[data.length - 1].id);i++)
if(Number(data[k].id) === i)
arr.push(data[k++]);
else
arr.push({})
//now you can reference like so:
alert(arr[5 - offset].name) // alerts "myname"
Make the result from ajax call like this:
{ "11": {
"name":"sourabh",
"userid":"soruabhbajaj",
"id":"11",
"has_profile_image":"0" },
"12": {
"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0"
}}
this way you can use it from javascript like this:
userName = jsonResponse[id].name
var data = [{"name":"sourabh",
"userid":"soruabhbajaj",
"id":"11",
"has_profile_image":"0" },
{"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0" }]
for(var i in data)
if(data[i]["id"] == 11)
alert(data[i].name);
It's very simple :)
Either search the array each time
function getUser(users, id) {
var user = null;
$.each(users, function() {
if (this.id === id) {
user = this;
return false; // break out of loop
}
});
return user
}
or create a reusable lookup table (assumes unique user ids):
function toLookup(users) {
var lookup = {};
$.each(users, function() {
lookup[this.id] = this;
});
return lookup;
}
function getUser(lookup, id) {
return lookup[id] || null;
}
精彩评论