How to get a subset of a javascript object's properties

后端 未结 27 1660
刺人心
刺人心 2020-11-21 22:46

Say I have an object:

elmo = { 
  color: \'red\',
  annoying: true,
  height: \'unknown\',
  meta: { one: \'1\', two: \'2\'}
};

I want to m

27条回答
  •  终归单人心
    2020-11-21 23:31

    You can use Lodash also.

    var subset = _.pick(elmo ,'color', 'height');
    

    Complementing, let's say you have an array of "elmo"s :

    elmos = [{ 
          color: 'red',
          annoying: true,
          height: 'unknown',
          meta: { one: '1', two: '2'}
        },{ 
          color: 'blue',
          annoying: true,
          height: 'known',
          meta: { one: '1', two: '2'}
        },{ 
          color: 'yellow',
          annoying: false,
          height: 'unknown',
          meta: { one: '1', two: '2'}
        }
    ];
    

    If you want the same behavior, using lodash, you would just:

    var subsets = _.map(elmos, function(elm) { return _.pick(elm, 'color', 'height'); });
    

提交回复
热议问题