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

后端 未结 27 1686
刺人心
刺人心 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:38

    Destructuring assignment with dynamic properties

    This solution not only applies to your specific example but is more generally applicable:

    const subset2 = (x, y) => ({[x]:a, [y]:b}) => ({[x]:a, [y]:b});
    
    const subset3 = (x, y, z) => ({[x]:a, [y]:b, [z]:c}) => ({[x]:a, [y]:b, [z]:c});
    
    // const subset4...etc.
    
    
    const o = {a:1, b:2, c:3, d:4, e:5};
    
    
    const pickBD = subset2("b", "d");
    const pickACE = subset3("a", "c", "e");
    
    
    console.log(
      pickBD(o), // {b:2, d:4}
      pickACE(o) // {a:1, c:3, e:5}
    );

    You can easily define subset4 etc. to take more properties into account.

    0 讨论(0)
  • 2020-11-21 23:39

    I suggest taking a look at Lodash; it has a lot of great utility functions.

    For example pick() would be exactly what you seek:

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

    fiddle

    0 讨论(0)
  • 2020-11-21 23:43

    One more solution:

    var subset = {
       color: elmo.color,
       height: elmo.height 
    }
    

    This looks far more readable to me than pretty much any answer so far, but maybe that's just me!

    0 讨论(0)
  • 2020-11-21 23:43

    This works for me in Chrome console. Any problem with this?

    var { color, height } = elmo
    var subelmo = { color, height }
    console.log(subelmo) // {color: "red", height: "unknown"}
    
    0 讨论(0)
  • 2020-11-21 23:46

    I am adding this answer because none of the answer used Comma operator.

    It's very easy with destructuring assignment and , operator

    const object = { a: 5, b: 6, c: 7  };
    const picked = ({a,c} = object, {a,c})
    
    console.log(picked);

    0 讨论(0)
  • 2020-11-21 23:46

    How about:

    function sliceObj(obj) {
      var o = {}
        , keys = [].slice.call(arguments, 1);
      for (var i=0; i<keys.length; i++) {
        if (keys[i] in obj) o[keys[i]] = obj[keys[i]];
      }
      return o;
    }
    
    var subset = sliceObj(elmo, 'color', 'height');
    
    0 讨论(0)
提交回复
热议问题