如何获取JavaScript对象中指定键的索引值
获取JavaScript对象中指定键的索引值
原始对象
{ "Home work": [ { "id": 5, "student_id": 2, "activity_id": 3, "checked": 1, "checked_at": "2023-02-07 06:03:06", "completed": 1, "created_at": "2023-02-06T12:31:22.000000Z", "updated_at": "2023-02-07T06:03:11.000000Z", "activity_category_name": "Home work" }, { "id": 2, "student_id": 2, "activity_id": 2, "checked": 1, "checked_at": "2023-02-07 06:03:38", "completed": 0, "created_at": "2023-02-06T10:44:31.000000Z", "updated_at": "2023-02-07T06:03:38.000000Z", "activity_category_name": "Home work" } ], "Daily activity": [ { "id": 1, "student_id": 2, "activity_id": 1, "checked": 1, "checked_at": "2023-02-05 11:18:56", "completed": 1, "created_at": "2023-02-05T10:40:25.000000Z", "updated_at": "2023-02-05T11:18:56.000000Z", "activity_category_name": "Daily activity" } ]}
需求
获取键"Home work"对应的索引值,预期结果为0。
尝试的代码
for((val, index) in array) { console.log(val) // output 'Home work : [...]' console.log(index) // output 'Home work' }
这段代码中index输出的是键名而非索引值,需要修正。
解决方案
JavaScript对象本质是键值对集合,本身没有“索引”概念(ES6+虽保留插入顺序,但仍不是数组结构)。要获取键的位置,需先提取对象的键为数组,再通过数组方法处理:
方法1:用Object.keys()提取键数组,再用indexOf()查找
const obj = { /* 你的原始对象 */ }; const keysArray = Object.keys(obj); const targetIndex = keysArray.indexOf("Home work"); console.log(targetIndex); // 输出0
方法2:用Object.entries()遍历并记录索引
如果需要在遍历过程中获取索引,可结合forEach:
const obj = { /* 你的原始对象 */ }; Object.entries(obj).forEach(([key, value], index) => { if (key === "Home work") { console.log(index); // 输出0 } });
注意事项
for...in遍历的是对象的键名,不是数组索引,不能用它直接获取键的位置。- 若业务逻辑高度依赖键的顺序,建议初始就用数组存储结构,避免依赖对象的插入顺序特性(部分旧环境可能不支持)。
内容的提问来源于stack exchange,提问作者muntasir
相关产品推荐
相关产品推荐

