JQuery.map () returns without undefined

I have an array of objects and I want to create a new array with only id. Some entries have id, while others do not.

So, I have something like:

var myMap = arr.map(function(e) {
    return e.id;
});

console.log(myMap); // [undefined, 2, 3, 4]

I would like him to return only [2, 3, 4]if possible.

This JSFiddle should explain a little better: http://jsfiddle.net/dmathisen/Lnmj0w8k/

+4
source share
3 answers

This is not possible with just Array.map, you should also filter.

var myMap = arr.map(function(e) {
    return e.id;
}).filter(function(x) {
    return typeof x !== 'undefined';
});

Since identifiers are always strings, you can also do this in the same way.

var myMap = arr.map(function(e) {
    return 'id' in e ? e.id : false;
}).filter(Boolean);

Fiddle

+11
source
var myMap = arr.filter(function(e) {
        return e.hasOwnProperty("id")
    }).map(function(e) {
    return e.hasOwnProperty("id") ? e.id : null;
});

http://jsfiddle.net/Lnmj0w8k/11/

+2

, jQuery, , map filter .

However, if you combine jQuery with the popular Underscore.js library, the problem becomes trivial thanks to the compact Underscore method:

var myMap = arr.map(function(e) {
    return e.id;
});
myMap = _(myMap).compact();

But if you use Underscore, there is an even easier way to do the same, because Underscore has a method specifically for extracting a specific property from an object:

var myMap = _(arr).pluck('id');
myMap = _(myMap).compact();

You can even connect the two together:

var myMap = _(arr).chain().pluck('id').compact().value();

or you can invest in the Greids Underscore library to get what I consider the easiest solution:

var myMap = _(arr).pluck_('id').compact();
0
source

All Articles