About user underscore.map

I have the following object

{one : 1, two : 2, three : 3}

and i would like

[1,2]

Here is my code

_.map({one : 1, two : 2, three : 3}, function(num, key){ 
         if (key==='one' || key==='two') {
             return num;
         } 
}); // [1, 2, undefined]

Actually, I would like to [1,2]

How to improve the code? thank

+5
source share
6 answers

Are you sure you want to use _.pickand _.values:

_.values( _.pick( obj, "one", "two" ) )
+9
source

I do not think that there is a built-in feature for this (for example, in you can use flatMapfor this purpose). ATconsider chained mapand filter:

_({one : 1, two : 2, three : 3}).
  chain().
  map(function(num, key){ 
    if (key==='one' || key==='two') {
      return num;
    }
  }).
  filter(function(num) {
    return num !== undefined
  }).
  value();

UPDATE (for @ZacharyK's comment): or use reject, complementary filter:

reject(function(num) {
  return num === undefined
})
+3
source

: map, compact

:

myArray = _.map({one : 1, two : 2, three : 3}, function(num, key){ 
         if (key==='one' || key==='two') {
             return num;
         } 
    });

myArray = _.compact(myArray)

, .

_ ():.

. JavaScript, false, null, 0, "", undefined NaN .

+2
source

Other answers will include (at least) two loops along the length of the object. Do you really want to _.reduce:

_.reduce({ one : 1, two : 2, three : 3 }, function ( out, num, key ) { 
    if ( key === 'one' || key === 'two' ) {
        out.push( num );
    }
    return out;
}, []);
// [1, 2]

This will give you your answer, compressed as you like, just one loop through your object.

+2
source

Break it into two steps. First use a filter to select the desired values, then use the map to get the values

_({..}).chain()
       .filter(function(num, key){
            return key ==='one'||key==='two';
        })
       map(function (num,key){
            return num;
       }).values()
0
source

Why don't you use:

_.map(['one','two'], function(key) { return obj[key]; });

which is rated as [1, 2]

See (although due to node replacement I have to indicate an underscore __):

> var __ = require('underscore');
> var obj = {one : 1, two : 2, three : 3};
> __.map(['one','two'], function(key) { return obj[key]; });
[ 1, 2 ]
-1
source

All Articles