3

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'

Brad Christie
102k16 gold badges160 silver badges200 bronze badges
asked Jun 21, 2011 at 15:27
0

5 Answers 5

5
function findStuff(jsonobject, propertyToFind, valueToFind)
{
 for (var i = 0; i < jsonobject.length; i++) {
 if (jsonobject[i][propertyToFind] === valueToFind)
 return jsonobject[i];
 }
 return null;
}
answered Jun 21, 2011 at 15:32
Sign up to request clarification or add additional context in comments.

Comments

1
for(var i=0; i<stuff.length; i++){
 var item = stuff[i];
 if(item.Name=='From')
 ....
}
answered Jun 21, 2011 at 15:30

Comments

1
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.

answered Jun 21, 2011 at 15:31

Comments

1
$.each('stuff', function(key,value)
{
 if (key == 'Name' && value == 'From')
 {
 alert('got it!');
 }
});
answered Jun 21, 2011 at 15:32

Comments

0

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/

answered Jan 7, 2014 at 7:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.