如何根据指定键名数组查找JavaScript对象中存在或缺失的对应键
解决方案
你可以通过Array.prototype.filter()分别过滤出存在和缺失的键,调整后的代码如下:
const obj = {Password: '123456', Username: 'MeMyselfAndI'} const checkFields= ['Method', 'Password', 'Username','email'] // 筛选存在的键 const existedKeys = checkFields.filter(key => obj.hasOwnProperty(key)) // 筛选缺失的键 const missingKeys = checkFields.filter(key => !obj.hasOwnProperty(key)) console.log('存在的键:', existedKeys) // 输出 ['Password', 'Username'] console.log('缺失的键:', missingKeys) // 输出 ['Method', 'email']
如果需要避免两次遍历数组,也可以用Array.prototype.reduce()单次遍历拿到所有结果:
const obj = {Password: '123456', Username: 'MeMyselfAndI'} const checkFields= ['Method', 'Password', 'Username','email'] const { existedKeys, missingKeys } = checkFields.reduce((acc, key) => { obj.hasOwnProperty(key) ? acc.existedKeys.push(key) : acc.missingKeys.push(key) return acc }, { existedKeys: [], missingKeys: [] }) console.log(existedKeys, missingKeys)
内容的提问来源于stack exchange,提问作者Taieb
相关产品推荐
相关产品推荐

