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

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

    Good-old Array.prototype.reduce:

    const selectable = {a: null, b: null};
    const v = {a: true, b: 'yes', c: 4};
    
    const r = Object.keys(selectable).reduce((a, b) => {
      return (a[b] = v[b]), a;
    }, {});
    
    console.log(r);
    

    this answer uses the magical comma-operator, also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

    if you want to get really fancy, this is more compact:

    const r = Object.keys(selectable).reduce((a, b) => (a[b] = v[b], a), {});
    

    Putting it all together into a reusable function:

    const getSelectable = function (selectable, original) {
      return Object.keys(selectable).reduce((a, b) => (a[b] = original[b], a), {})
    };
    
    const r = getSelectable(selectable, v);
    console.log(r);
    

提交回复
热议问题