Reputation: 22530
I am getting my head around lodash for js and trying to select the object property with the name 'one' from this object by using the id key:
{
"one": {
"id":"peter",
"somevalue":1
},
"two": {
"id":"john",
"somevalue":1
}
}
So as a result I would like:
{
"id":"peter",
"somevalue":1
}
Sorry I updated the question: How can I accomplish this with lodash returning this result based on the name in this case 'one' by using the key , id='peter'?
Upvotes: 1
Views: 9455
Reputation: 7078
With Lodash
(#1):
const value = _.find(obj, prop => prop.id === 'peter');
With Lodash
(#2):
const value = _.find(obj, {id: 'peter'});
With Lodash
(#3): (credit to hughes)
const value = _.find(obj, 'id', 'peter');
Plain JS:
const key = Object.keys(obj).find(key => obj[key].id === 'peter');
const value obj[key];
Future JS:
const value = Object.values(obj).find(prop => prop.id === 'peter');
Upvotes: 7
Reputation: 5473
More documentation on filter here: https://lodash.com/docs#filter
var obj = {
"one": {
"id":"peter",
"somevalue":1
},
"two": {
"id":"john",
"somevalue":1
}
};
console.log(_.filter(obj, {id:"peter"}));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
Upvotes: 1