Don P
Don P

Reputation: 63587

Use underscore.js to find an object in another object

Using underscore.js, what is the simplest way to get the ID of the object with the person named "Ted"?

Example:

var people = {
  1: { name: "Ted" },
  2: { name: "Will" },
  3: { name: "James" }
}

Raw JS solution:

var personId;

for (id in people) {
  if (people[id].name === "Ted") {
    personId = id;
  }
}

Upvotes: 2

Views: 45

Answers (2)

kevin ternet
kevin ternet

Reputation: 4612

In case there are several id with the same name, I propose you a raw JS solution that gives you an object inside only remains properties matching :

var people = {
  1: { name: "Ted" },
  2: { name: "Will" },
  3: { name: "James" },
  4: { name: "Ted" }
};
var keys = Object.keys(people);
result = {};
keys.forEach(item => {if (people[item].name === "Ted")result[item] = {name: people[item].name}});
console.log(result); // { '1': { name: 'Ted' }, '4': { name: 'Ted' } }

Upvotes: 0

martriay
martriay

Reputation: 5742

With findKey:

var personId = _.findKey(people, function(obj) { return obj.name === 'Ted' });

Blender suggests this simplified version:

var personId = _.findKey(people, { name: 'Ted' });

Upvotes: 2

Related Questions