bob_hardy1703
bob_hardy1703

Reputation: 45

Find an object and its properties within a larger object with javascript/jquery

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"}

Upvotes: 0

Views: 74

Answers (4)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

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];

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134167

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

Upvotes: 0

Renato Gama
Renato Gama

Reputation: 16519

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);

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227200

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;
    }
}

Upvotes: 4

Related Questions