maxpayne maxpayne - 20 days ago 6
Javascript Question

Javascript: Filter out on an array of objects and pick based on key, not value

Im trying to loop through an array of objects, which have different keys. Is there a way that I can pick an object based on they key?

var array = [
{
"1400": "Accident and Health"
},
{
"100": "Life"
},
{
"1300": "Pension"
}
]
var a = "100";
var pop = _.pick(array,a);
console.log(pop);


Desired output:

Life

Thank you!

Answer

You could use the in operator.

var array = [{ 1400: "Accident and Health" }, { 100: "Life" }, { 1300: "Pension" }];

var result = (key => array.find(item => key in item)[key])(100);

console.log(result);