如何在JavaScript中通过属性键而非值获取JS对象数组中指定属性的索引
解决方案
你想要的通过键匹配获取数组中对应对象的索引的需求,无法直接使用原生indexOf()实现。indexOf()的核心逻辑是匹配数组元素和传入参数的全等(===)关系,不能自定义匹配规则检测对象是否包含指定键。
推荐实现方式
使用Array.prototype.findIndex()方法自定义匹配规则即可满足需求:
原始示例代码:
var sampleObj = [{prop1 : ""}, {prop2 : ""}, {propArr : [{key : "", value : ""}, {key : "", value : ""}]}];
功能实现代码:
// 匹配包含propArr键的元素,返回对应索引 const index = sampleObj.findIndex(item => { return Object.prototype.hasOwnProperty.call(item, 'propArr') })
findIndex()会遍历数组所有元素,返回第一个符合回调规则的元素索引,无匹配项时返回-1- 使用
Object.prototype.hasOwnProperty.call()做键检测是为了避免原型链继承的属性干扰判断,兼容性和安全性更高。
封装类indexOf调用方法
如果你想要和预期相近的调用形式,可以自行封装数组扩展方法:
// 扩展数组原型,添加按键查找索引的方法 Array.prototype.indexOfKey = function(targetKey) { return this.findIndex(item => Object.prototype.hasOwnProperty.call(item, targetKey)) } // 调用效果和要求的逻辑一致 const index = sampleObj.indexOfKey('propArr')
内容的提问来源于stack exchange,提问作者Mohamed Mounir
相关产品推荐
相关产品推荐

