I have an object array and I want to create a new array with the id
s only. Some records have id
and others don't.
So I have something like:
var myMap = arr.map(function(e) {
return e.id;
});
console.log(myMap); // [undefined, 2, 3, 4]
I'd like it to return just [2, 3, 4]
, if possible.
This JSFiddle should explain a little better: http://jsfiddle.net/dmathisen/Lnmj0w8k/
It's not possible with just Array.map, you have to filter as well.
var myMap = arr.map(function(e) {
return e.id;
}).filter(function(x) {
return typeof x !== 'undefined';
});
As the ID's are always strings, you can do it like this as well
var myMap = arr.map(function(e) {
return 'id' in e ? e.id : false;
}).filter(Boolean);
FIDDLE
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