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

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

    If you are using ES6 there is a very concise way to do this using destructuring. Destructuring allows you to easily add on to objects using a spread, but it also allows you to make subset objects in the same way.

    const object = {
      a: 'a',
      b: 'b',
      c: 'c',
      d: 'd',
    }
    
    // Remove "c" and "d" fields from original object:
    const {c, d, ...partialObject} = object;
    const subset = {c, d};
    
    console.log(partialObject) // => { a: 'a', b: 'b'}
    console.log(subset) // => { c: 'c', d: 'd'};
    

提交回复
热议问题