Removing object properties with Lodash

后端 未结 8 1405
旧巷少年郎
旧巷少年郎 2021-02-02 05:30

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,
   lna         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 05:41

    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);

    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);

提交回复
热议问题