Copying data from JSON array to an JS Object for jQuery Autocomplete
I'm trying to use the Autocomplete plugin in jQuery to allow a user to search for a person's name quickly using a text field and return their Facebook user id. The JSON that Facebook provides is along these lines:
{
"data":[
{
"name":"Emma Alexander",
"id":"8110855"
},
{
"name":"Dave Suckow",
"id":"19546358"
},
{
"name":"Jessica Willits",
"id":"45734687"
}
]
}
However, I'd like to do the searching locally, rather than retrieving Facebook JSON every time, so I think I need to copy all of the names and IDs into a local JavaScript Object (I think that's the best 开发者_运维百科way to do it?) and then use jQuery to search through those names instead. When the user selects a name from the text field, it will call another function and pass it the selected person's Facebook ID.
However, I'm not sure if this is the best way, or how I would really go about implementing it.
If anybody could offer a couple of small code examples, especially for copying the data from Facebook's JSON to a local Javascript object and then searching through that object, it would be massively appreciated! :)
Thanks a lot
Hmm..You could do something like this...
var jsonval=
({
"data":[
{
"name":"Emma Alexander",
"id":"8110855"
},
{
"name":"Dave Suckow",
"id":"19546358"
},
{
"name":"Jessica Willits",
"id":"45734687"
}
]
})
var name=new Array();
var id=new Array();
for(var i=0;i<jsonval.data.length;i++){
name.push(jsonval.data[i].name);
id.push(jsonval.data[i].id);
}
The arrays name
and id
will contain all the names and ids fetched from the JSON and searh all the values in the new arrays created...Thats one way... the other is you could save the JSON returned in the variable jsonval
and then every time search using the for loop that was used to push the values into an array...
I think your better off to just call the fb json every time because something could change between searching. that said if you made your ajsx call on load you could just set a var at the begining like this
searchdata = "";
then once your ajax call is made and you get your json data just set the variable to the dataresult bobs your uncle
searchdat = jsonresult;
make sense ?
Not tested, but the following function takes a search string and the data object and searches in the name field, and returns the user's id
, or null if no match found.
function searchUser(search, data) {
var matchedUser = null;
$.each(data, function () {
if (this.name.indexOf(search) !== -1) {
matchedUser = this;
}
});
return matchedUser && matchedUser.id;
}
精彩评论