Search code examples
javascriptlodash

Removing object properties with Lodash


I have to remove unwanted object properties that do not match my model. How can I achieve it with Lodash?

My model is:

var model = {
   fname: null,
   lname: null
}

My controller output before sending to the server will be:

var credentials = {
    fname: "xyz",
    lname: "abc",
    age: 23
}

I am aware I can use

delete credentials.age

but what if I have lots of unwanted properties? Can I achieve it with Lodash?


Solution

  • Get a list of properties from model using _.keys(), and use _.pick() to extract the properties from credentials to a new object:

    var model = {
       fname:null,
       lname:null
    };
    
    var credentials = {
        fname:"xyz",
        lname:"abc",
        age:23
    };
    
    var result = _.pick(credentials, _.keys(model));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

    If you don't want to use Lodash, you can use Object.keys(), and Array.prototype.reduce():

    var model = {
       fname:null,
       lname:null
    };
    
    var credentials = {
        fname:"xyz",
        lname:"abc",
        age:23
    };
    
    var result = Object.keys(model).reduce(function(obj, key) {
      obj[key] = credentials[key];
      return obj;
    }, {});
    
    console.log(result);