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

后端 未结 27 1687
刺人心
刺人心 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"}
      
    0 讨论(0)
  • 2020-11-21 23:47

    Using Object Destructuring and Property Shorthand

    const object = { a: 5, b: 6, c: 7  };
    const picked = (({ a, c }) => ({ a, c }))(object);
    
    console.log(picked); // { a: 5, c: 7 }


    From Philipp Kewisch:

    This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

    let unwrap = ({a, c}) => ({a, c});
    
    let unwrap2 = function({a, c}) { return { a, c }; };
    
    let picked = unwrap({ a: 5, b: 6, c: 7 });
    
    let picked2 = unwrap2({a: 5, b: 6, c: 7})
    
    console.log(picked)
    console.log(picked2)

    0 讨论(0)
  • 2020-11-21 23:47

    Use pick method of lodash library if you are already using.

    var obj = { 'a': 1, 'b': '2', 'c': 3 };
    
    _.pick(object, ['a', 'c']);
    
    // => { 'a': 1, 'c': 3 }
    

    https://lodash.com/docs/4.17.10#pick

    0 讨论(0)
提交回复
热议问题