Getting the values for a specific key from all objects in an array
You could map
:
permittedValues = array.map(function(value) {
return value.key;
});
In ES6/ES2015 it's even prettier with arrow functions:
permittedValues = array.map(value => value.key);
It might be prettier, but it's probably not faster than a for()
loop.
Using lodash,
Since lodash 4.x the _.pluck function has been removed in support to map function.
so you can achieve the desired task by:
import _ from 'lodash'
_.map(items, 'key');
Ref: What happened to Lodash _.pluck?
Pure Javascript ES6
array.map(value => value.key);
Underscore/Lodash
_.map(value,'key')
If you are using ES6 javascript version you can do something like the one below:
const arrayData = [
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
const foodBar = arrayData.find(item => item.key === "baz");
const resultValue = foodBar['value']; // here the extracted value is by key