JavaScript选取(picking)和反选(rejecting)对象的属性方法
有时候我们需要将一个对象的某些属性选取出来,比方说我们有一个用数组表示的数据库表,我们需要一些函数来select(选取)几个字段:
functionpick(obj,keys){ returnkeys.map(k=>kinobj?{[k]:obj[k]}:{}) .reduce((res,o)=>Object.assign(res,o),{}); } constrow={ 'accounts.id':1, 'client.name':'JohnDoe', 'bank.code':'MDAKW213' }; consttable=[ row, {'accounts.id':3,'client.name':'SteveDoe','bank.code':'STV12JB'} ]; pick(row,['client.name']);//取到了clientname table.map(row=>pick(row,['client.name']));//取到了一系列clientname
在pick函数中用到了一点小技巧。首先,我们用map遍历了键名数组(keys),每次都会返回一个包含当前键名(key)的对象(如果在目标对象(obj)中没有当前键名,就会返回空对象)。然后我们用reduce把返回的所有单个键-值对象和合并到一个对象中。
但是,如果我们想反选(reject)属性/键名呢?改造一下我们的函数就好了:
functionreject(obj,keys){ returnObject.keys(obj) .filter(k=>!keys.includes(k)) .map(k=>({[k]:obj[k]})) .reduce((res,o)=>Object.assign(res,o),{}); } //或者,利用pick functionreject(obj,keys){ constvkeys=Object.keys(obj) .filter(k=>!keys.includes(k)); returnpick(obj,vkeys); } reject({a:2,b:3,c:4},['a','b']);//=>{c:4}
总结
以上所述是小编给大家介绍的JavaScript选取(picking)和反选(rejecting)对象的属性方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!