JavaScript如何根据子属性值获取对象banco对应的顶层属性名
实现方案
单匹配结果方法(返回第一个符合条件的顶层键)
如果只需要拿到第一个匹配的顶层属性名,直接遍历匹配即可:
function getFirstMatchedKey(obj, propName, propValue) { for (const key of Object.keys(obj)) { if (obj[key][propName] === propValue) { return key } } return null } // 你的场景调用,返回期望结果 const targetKey = getFirstMatchedKey(banco, 'ocupacao', 'Entregador 📦') // targetKey 的值为 "553592729970@c.us"
多匹配结果方法(返回所有符合条件的顶层键数组)
如果存在多个子属性符合匹配条件,需要全部返回的场景用过滤方法:
function getAllMatchedKeys(obj, propName, propValue) { return Object.keys(obj).filter(key => obj[key][propName] === propValue) } // 你的场景调用 const targetKeys = getAllMatchedKeys(banco, 'ocupacao', 'Entregador 📦') // targetKeys 的值为 ["553592729970@c.us", "553599242101@c.us"]
内容的提问来源于stack exchange,提问作者Bruno Custódio
相关产品推荐
相关产品推荐

