Removing object properties with Lodash

后端 未结 8 1399
旧巷少年郎
旧巷少年郎 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:45

    You can easily do this using _.pick:

    var model = {
      fname: null,
      lname: null
    };
    
    var credentials = {
      fname: 'abc',
      lname: 'xyz',
      age: 2
    };
    
    var result = _.pick(credentials, _.keys(model));
    
    
    console.log('result =', result);

    But you can simply use pure JavaScript (specially if you use ECMAScript 6), like this:

    const model = {
      fname: null,
      lname: null
    };
    
    const credentials = {
      fname: 'abc',
      lname: 'xyz',
      age: 2
    };
    
    const newModel = {};
    
    Object.keys(model).forEach(key => newModel[key] = credentials[key]);
    
    console.log('newModel =', newModel);

提交回复
热议问题