Keeping only certain properties in a JavaScript object

后端 未结 11 1024
时光说笑
时光说笑 2020-12-20 11:05

I have an object. I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this o

11条回答
  •  醉酒成梦
    2020-12-20 12:00

    Lodash has a function called pick which does what you're describing. I know that including a library isn't ideal, but you can also cherry-pick functions when using bundles, etc.

    var myObj={
        p1:123,
        p2:321,
        p3:{p3_1:1231,p3_2:342},
        p4:'23423',
        //....
        p99:{p99_1:'sadf',p99_2:234},
        p100:3434
    }
    
    var newObj = _.pick(myObj, 'p1', 'p2', 'p100')
    

提交回复
热议问题