Removing object properties with Lodash

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

    You can approach it from either an "allow list" or a "block list" way:

    // Block list
    // Remove the values you don't want
    var result = _.omit(credentials, ['age']);
    
    // Allow list
    // Only allow certain values
    var result = _.pick(credentials, ['fname', 'lname']);
    

    If it's reusable business logic, you can partial it out as well:

    // Partial out a "block list" version
    var clean = _.partial(_.omit, _, ['age']);
    
    // and later
    var result = clean(credentials);
    

    Note that Lodash 5 will drop support for omit

    A similar approach can be achieved without Lodash:

    const transform = (obj, predicate) => {
      return Object.keys(obj).reduce((memo, key) => {
        if(predicate(obj[key], key)) {
          memo[key] = obj[key]
        }
        return memo
      }, {})
    }
    
    const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
    
    const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
    
    // Partials
    // Lazy clean
    const cleanL = (obj) => omit(obj, ['age'])
    
    // Guarded clean
    const cleanG = (obj) => pick(obj, ['fname', 'lname'])
    
    
    // "App"
    const credentials = {
        fname:"xyz",
        lname:"abc",
        age:23
    }
    
    const omitted = omit(credentials, ['age'])
    const picked = pick(credentials, ['age'])
    const cleanedL = cleanL(credentials)
    const cleanedG = cleanG(credentials)
    

提交回复
热议问题