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

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

    Adding my 2 cents to Ivan Nosov answer:

    In my case I needed many keys to be 'sliced' out of the object so it's becoming ugly very fast and not a very dynamic solution:

    const object = { a: 5, b: 6, c: 7, d: 8, aa: 5, bb: 6, cc: 7, dd: 8, aaa: 5, bbb: 6, ccc: 7, ffffd: 8, ab: 5, bc: 6, cd: 7, de: 8  };
    const picked = (({ a, aa, aaa, ab, c, cc, ccc, cd }) => ({ a, aa, aaa, ab, c, cc, ccc, cd }))(object);
    
    console.log(picked);
    

    So here is a dynamic solution using eval:

    const slice = (k, o) => eval(`(${k} => ${k})(o)`);
    
    
    const object    = { a: 5, b: 6, c: 7, d: 8, aa: 5, bb: 6, cc: 7, dd: 8, aaa: 5, bbb: 6, ccc: 7, ffffd: 8, ab: 5, bc: 6, cd: 7, de: 8  };
    const sliceKeys = '({ a, aa, aaa, ab, c, cc, ccc, cd })';
    
    console.log( slice(sliceKeys, object) );
    

提交回复
热议问题