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'

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;
}
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')
       ....
}

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.

Comments

1
$.each('stuff', function(key,value)
{
    if (key == 'Name' && value == 'From')
    {
         alert('got it!');
    }
});

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/

Comments

Your Answer

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.