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

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

    1. convert arguments to array

    2. use Array.forEach() to pick the property

      Object.prototype.pick = function(...args) {
         var obj = {};
         args.forEach(k => obj[k] = this[k])
         return obj
      }
      var a = {0:"a",1:"b",2:"c"}
      var b = a.pick('1','2')  //output will be {1: "b", 2: "c"}
      

提交回复
热议问题