Skip to main content
 首页 » 编程设计

javascript之使用 Lodash 删除对象属性

2024年04月18日9mfrbuaa

我必须删除与我的模型不匹配的不需要的对象属性。我怎样才能用Lodash实现它?

我的模型是:

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

在发送到服务器之前我的 Controller 输出将是:

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

我知道我可以使用

delete credentials.age 

但是如果我有很多不需要的属性怎么办?我可以用 Lodash 实现它吗?

请您参考如下方法:

您可以通过“允许列表”或“阻止列表”方式访问它:

// 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']); 

如果它是可重用的业务逻辑,您也可以将其部分化:

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

请注意,Lodash 5 将放弃对 omit 的支持

无需 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)