I have a case I keep coming across where I need to get just an object key - not the entire object - based on another key value in the same object, all from an array of objects.
So for example, if I have the following array of objects:
myArray = [
{
name: Person 1
type: alpha
},
{
name: Person 2
type: beta
},
{
name: Person 3
type: gamma
},
{
name: Person 4
type: beta
},
{
name: Person 5
type: gamma
},
];
So if I want to get just the name values for those objects with a type of 'beta', how would I do that? I prefer lodash, and I know how to use _.map or _.filter, e.g.
var newArray = _.map(myArray, function(item) {
return item.type === 'beta';
});
but those return the whole object. I suspect I can get what I want with chaining, but I'm not figuring out how I can do this.
Thanks.
To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
You can do this with the native Array.prototype.map()
. It'd look like this (using ES6 fat-arrow functions for conciseness):
myArray.filter(item => item.type === 'beta').map(item => item.name)
The ES5 form is:
myArray.filter(function(item) {return item.type === 'beta'})
.map(function(item) {return item.name})
Here's a lodash solution that uses map and filter.
var result = _(myArray).filter({ type: 'beta' }).map('name').value();
var myArray = [
{
name: 'Person 1',
type: 'alpha'
},
{
name: 'Person 2',
type: 'beta'
},
{
name: 'Person 3',
type: 'gamma'
},
{
name: 'Person 4',
type: 'beta'
},
{
name: 'Person 5',
type: 'gamma'
},
];
var result = _(myArray).filter({ type: 'beta' }).map('name').value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With