Underscore equivalent of _.pick for arrays

前端 未结 1 794
清歌不尽
清歌不尽 2021-02-04 08:34

I understand that pick is used to get back an object with only specified properties:

_.pick({name: \'moe\', age: 50, userid: \'moe1\'}, \'name\', \'age\');
=>         


        
1条回答
  •  生来不讨喜
    2021-02-04 09:07

    You have to use _.map and apply the same _.pick on all the objects.

    var data = [{name: 'moe1', age: 30, userid: 'moe1'},
                {name: 'moe2', age: 50, userid: 'moe1'},
                {name: 'moe3', age: 60, userid: 'moe1'}];
    
    var result = _.map(data, function(currentObject) {
        return _.pick(currentObject, "name", "age");
    });
    
    console.log(result);
    

    Output

    [ { name: 'moe1', age: 50 },
      { name: 'moe2', age: 50 },
      { name: 'moe3', age: 50 } ]
    

    If you want to get the objects in which the age is > 50, you might want to do, like this

    var data = [{name: 'moe1', age: 30, userid: 'moe1'},
                {name: 'moe2', age: 50, userid: 'moe1'},
                {name: 'moe3', age: 60, userid: 'moe1'}];
    
    function filterByAge(currentObject) {
        return currentObject.age && currentObject.age > 50;
    }
    
    function omitUserId(currentObject) {
        return _.omit(currentObject, "userid");
    }
    
    var result = _.map(_.filter(data, filterByAge), omitUserId);    
    console.log(result);
    

    Output

    [ { name: 'moe3', age: 60 } ]
    

    You can do the same with chaining, as suggested by rightfold, like this

    var result = _.chain(data).filter(filterByAge).map(omitUserId).value();
    

    0 讨论(0)
提交回复
热议问题