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

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

    There is nothing like that built-in to the core library, but you can use object destructuring to do it...

    const {color, height} = sourceObject;
    const newObject = {color, height};
    

    You could also write a utility function do it...

    const cloneAndPluck = function(sourceObject, keys) {
        const newObject = {};
        keys.forEach((obj, key) => { newObject[key] = sourceObject[key]; });
        return newObject;
    };
    
    const subset = cloneAndPluck(elmo, ["color", "height"]);
    

    Libraries such as Lodash also have _.pick().

提交回复
热议问题