4

I have an object array and I want to create a new array with the ids 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/

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

2
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/

Comments

0

As others have said, if you stick to pure jQuery your only option is to combine your map with a filter, or otherwise post-process the map results yourself.

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

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

But if you use Underscore, there's an even simpler way to do the same thing, because Underscore has a method specifically for extracting a certain property from an object:

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

You can even chain the two together:

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

or you can throw in the Underscore Grease library to get what I consider to be the simplest possible solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.