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

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

    TypeScript solution:

    function pick(
      obj: T,
      paths: Array
    ): Pick {
      const ret = Object.create(null);
      for (const k of paths) {
        ret[k] = obj[k];
      }
      return ret;
    }
    

    The typing information even allows for auto-completion:

    Credit to DefinitelyTyped for U extends keyof T trick!

    TypeScript Playground

提交回复
热议问题