Lou_Ds
Lou_Ds

Reputation: 551

js - Filter out attribute based on key

I have a js variable like:

var mylist = [[ {item: 'emp', pos:1}, {age: 21, name: 'AA'}, {age: 22, name: 'BB'}, ], ... ];

in my js script, I read

var out = (mylist[0].map(function(i, j){return i.age}))
total = out.length   // this has 3 -->  ['', '21', '22']

How do I filter out elements in the list and just return the ones with age keyword, so my total would be = ['21', '22']

I am new to js, so not sure how to handle the ?lambda? function to add a condition or filter out/ return "clean" data.

Upvotes: 1

Views: 55

Answers (1)

Nikhil
Nikhil

Reputation: 6641

You can use filter() after map() to remove those undefined values.

var mylist = [[ {item: 'emp', pos:1}, {age: 21, name: 'AA'}, {age: 22, name: 'BB'}]];

var out = mylist[0].map(i => i.age).filter(age => age);

console.log(out);

Upvotes: 2

Related Questions