Keeping only certain properties in a JavaScript object

后端 未结 11 1023
时光说笑
时光说笑 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 11:53

    Just re-initialise the object:

    myObj = {
        p1:   myObj.p1,
        p2:   myObj.p2,
        p100: myObj.p100
    };
    

    Another way is to delete certain properties, which is less effective:

    var prop = ['p1', 'p2', 'p100'];
    for (var k in myObj) {
        if (prop.indexOf(k) < 0) {
            delete myObj[k];
        }
    }
    

提交回复
热议问题