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

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

提交回复
热议问题