Keeping only certain properties in a JavaScript object

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

    You can code your own implementation of _.pick, and use it according to your needs.

    Having this snippet of code as the base for the following cases:

    const myObj={
        p1:123,
        p2:321,
        p3:{p3_1:1231,p3_2:342},
        p4:'23423',
        //....
        p99:{p99_1:'sadf',p99_2:234},
        p100:3434
    }
    let properties= ['p1','p2', 'p3', 'p100'];
    

    case 1:

    You want a shallow copy (with references to vector values)

    const myNewObj = properties.reduce((newObj,property)=>{newObj[property] = myObj[property]; return newObj}, {})
    // if we modify the original vector value of 'p3' in `myObj` we will modify the copy as well:
    
    myObj.p3.p3_1 = 99999999999;
    
    console.log(myNewObj); // { p1: 123,​​​​​​​​​​  p2: 321,​​​​​​​​​​  p3: { p3_1: 99999999999, p3_2: 42 },​​​​​​​​​​  p100: 3434 }​​​​​
    

    case 2:

    You want a deep copy (losing references to vector values)

    You can just use JSON utilities to that matter.

    const myNewObj2 = properties.reduce((newObj,property)=>{newObj[property] = JSON.parse(JSON.stringify(myObj[property])); return newObj},{})
    
    // no matter how hard you modify the original object, you will create a new independent object
    myObj.p3.p3_1 = 99999999999;
    
    console.log(myNewObj2) // { p1: 123, p2: 321, p3: { p3_1: 1231, p3_2: 342 }, p100: 3434 }​​​​​
    

    Reusing case 2 with a function

    You could implement a reducer to use it in different scenarios, like this one:

    function reduceSelectedProps(origin, properties){
      return (newObj,property)=>{
        newObj[property] = JSON.parse(JSON.stringify(origin[property]));
         return newObj
      }
    }
    

    So you could have a more elegant reuse of it:

    const myNewObj3 = properties.reduce(reduceSelectedProps(myObj, properties),{});
    // no matter how hard you modify the original object, you will create a new independent object
    myObj.p3.p3_1 = 99999999999;
    
    console.log(myNewObj3) // { p1: 123, p2: 321, p3: { p3_1: 1231, p3_2: 342 }, p100: 3434 }​​​​​
    

    disclaimers:

    This is only an example that does not handle Date, Set, Map or function values inside the properties. To deal with all these cases (and many others), it needs a really complex function with checks on the prototypes and all that stuff. At this point, consider reusing the work of other developers using any library that could do it. Lodash?

提交回复
热议问题