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

后端 未结 27 1659
刺人心
刺人心 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.

提交回复
热议问题