You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据指定键名数组查找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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:27:00