Reputation: 63587
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
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