Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key value based on value of another key in object

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.

like image 567
wonder95 Avatar asked Mar 13 '17 04:03

wonder95


People also ask

How do you find the specific key of an object?

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.

How do I get the key of an array of objects?

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.


2 Answers

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})
like image 175
S McCrohan Avatar answered Sep 22 '22 02:09

S McCrohan


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>
like image 37
ryeballar Avatar answered Sep 20 '22 02:09

ryeballar