Keeping only certain properties in a JavaScript object

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

    You could create a view on your first object, some kind of proxy that would only keep the desired properties on sight.
    For instance the following function will create a view that allows to both read and write the underlying object, keeping only the choosen properties.
    You can make it readonly very easily, by just removing the setter.
    You might also want to seal the proxy object, so that no later modification can me made to it.

    function createView(obj, propList) {
        var proxy = {};     
        for (var propIndex in propList) {    
             var prop=propList[propIndex];
             Object.defineProperty(proxy, prop, 
                    {  enumerable : true , 
                       get : getter.bind(obj,prop), 
                       set : setter.bind(obj,prop)   } );
    
        }    
      return proxy;
    }
    
    function getter(prop) { return this[prop] ; }
    
    function setter(prop, value) { return this[prop] = value ; }
    

    An example of use would be :

    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 objView = createView(myObj, ['p1', 'p2', 'p100']);
    

    Here, objView 'reflects' the desired properties of myObj. You can look at the small jsbin i made here :

    http://jsbin.com/munudewa/1/edit?js,console

    results :

    "on objView, p1:123 p2:321 p100:3434 and p4 (not in view) is : undefined"
    "modifiying, on the view,  p1 to 1000 and p2 to hello "
    "on objView, p1:1000 p2:hello p100:3434 and p4 (not in view) is : undefined"
    "modifiying, on the viewed object,  p1 to 200 and p2 to bye "
    "on objView, p1:200 p2:bye p100:3434 and p4 (not in view) is : undefined"
    

    notice that :
    1) you can overwrite an object by its view, only keeping desired properties.
    2) you can save in a hidden property / in a closure, the original object, so you can later change the properties you expose.

提交回复
热议问题