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

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

    Destructuring into dynamically named variables is impossible in JavaScript as discussed in this question.

    To set keys dynamically, you can use reduce function without mutating object as follows:

    const getSubset = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {});
    
    const elmo = { 
      color: 'red',
      annoying: true,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    }
    
    const subset = getSubset(elmo, 'color', 'annoying')
    console.log(subset)

    Should note that you're creating a new object on every iteration though instead of updating a single clone. – mpen

    below is a version using reduce with single clone (updating initial value passed in to reduce).

    const getSubset = (obj, ...keys) => keys.reduce((acc, curr) => {
      acc[curr] = obj[curr]
      return acc
    }, {})
    
    const elmo = { 
      color: 'red',
      annoying: true,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    }
    
    const subset = getSubset(elmo, 'annoying', 'height', 'meta')
    console.log(subset)

提交回复
热议问题