I'm not sure how to accomplish this following given this array of JSON objects:
var stuff = [
{
'Address' : '123 Street',
'Name' : 'From'
},
{
'Address' : '456 Avenue',
'Name' : 'To'
}
]
So what I would like to be able to do is query this array of objects based on one of the properties, in this case 'Name', and return the entire object that matches the query.
Is there anyway to do this with jquery or just regular javascript?
For example I'd like to return the whole object where Name === 'From'
5 Answers 5
function findStuff(jsonobject, propertyToFind, valueToFind)
{
for (var i = 0; i < jsonobject.length; i++) {
if (jsonobject[i][propertyToFind] === valueToFind)
return jsonobject[i];
}
return null;
}
Comments
for(var i=0; i<stuff.length; i++){
var item = stuff[i];
if(item.Name=='From')
....
}
Comments
function findByName(ary,name){
for (var a = 0; a < ary.length; a++){
if (ary[a].Name == name)
return stuff[a];
}
return {};
}
var match = findByName(stuff,'From');
Use a loop to go through the objects. Use .Name off the object to read the JSON object's property value.
Comments
$.each('stuff', function(key,value)
{
if (key == 'Name' && value == 'From')
{
alert('got it!');
}
});
Comments
Instead of writing custom functions, you can use this JS lib - DefiantJS (defiantjs.com). Which extends the global object JSON with the method "search". With this method, you can search a JSON structure with XPath expressions and it'll return array with the matches (empty array if no matches were found).
var stuff = [
{
"Address": "123 Street",
"Name": "From"
},
{
"Address": "456 Avenue",
"Name": "To"
}
],
res = JSON.search( stuff, '//*[Name = "From"]' );
console.log( res[0].Address );
// 123 Street
Here is a working fiddle:
http://jsfiddle.net/hbi99/4H57C/