0
family = {
  'person1':[{"id":"1111","name":"adam", "sex":"male", "born":"USA"}],
  'person2':[{"id":"2222","name":"sarah", "sex":"female", "born":"Canada"}],
  'person3':[{"id":"3333","name":"adam", "sex":"male", "born":"USA"}]
};

Given the family object above, how do I extract all the properties (id, name, sex, born) of one of the person objects that have a specific id (or name) value? eg id=1111

So ideally I can get a new object personInQuestion that I can manipulate, where:

personInQuestion = {"id":"1111","name":"adam", "sex":"male", "born":"USA"}

4 Answers 4

4

Loop through the object, and grab the element that matches.

var search = 1111;

var personInQuestion = {};
for(var x in family){
    var item = family[x][0];
    if(item.id == search){
        personInQuestion = item;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I dont think jQuery is the best tool for this, instead I suggest you taking a look at the Where method that the Backbone library offers. Not sure if it would be overkill.

Usage is like this:

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

alert(musketeers.length);

1 Comment

I would say that integrating Backbone for this would probably be overkill since Backbone is more of a framework. Using a more utility-oriented library like Underscore may be more appropriate.
0

jQuery does not provide selectors for JSON (JavaScript Object) data, so you would need to iterate over the object. For example:

result =  null;
$.each(family, function(i, v) {
  if (v.id === "1111" && v.name === "adam" ...) {
    result = v;
    return;
  }
});

Comments

0

Here's an example of Rob Hruska's suggestion(in a comment) to use Underscore.

family = {
  'person1':[{"id":"1111","name":"adam", "sex":"male", "born":"USA"}],
  'person2':[{"id":"2222","name":"sarah", "sex":"female", "born":"Canada"}],
  'person3':[{"id":"3333","name":"adam", "sex":"male", "born":"USA"}]
};

var searchId = 1111;

var person = _.find(family, function(item) { return item[0].id == searchId; })[0];

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.