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

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

    Using the "with" statement with shorthand object literal syntax

    Nobody has demonstrated this method yet, probably because it's terrible and you shouldn't do it, but I feel like it has to be listed.

    var o = {a:1,b:2,c:3,d:4,e:4,f:5}
    with(o){
      var output =  {a,b,f}
    }
    console.log(output)

    Pro: You don't have to type the property names twice.

    Cons: The "with" statement is not recommended for many reasons.

    Conclusion: It works great, but don't use it.

提交回复
热议问题