Keeping only certain properties in a JavaScript object

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

    var myObj = {a: 1, b: 2, c:3};
    
    function keepProps(obj, keep) {
        for (var prop in obj) {
            if (keep.indexOf( prop ) == -1) {
                delete obj[prop];
            }             
        }
    }
    
    keepProps(myObj, ['a', 'b']);
    console.log(myObj);
    

    http://jsfiddle.net/mendesjuan/d8Sp3/2/

提交回复
热议问题