如何通过索引获取嵌套JavaScript对象中的数据?
如何通过索引获取嵌套JavaScript对象中的数据?
我明白你的问题啦——你手里的sundriesIncreases是个嵌套对象,键是month1、month2这种字符串格式,不是数组,所以直接用数字索引(比如index)去访问肯定找不到对应的属性,这就是你之前代码失效的核心原因。我来给你拆解问题,再提供几个可行的解决方案:
先说说你之前代码的问题
- 第一种写法里,
data.sundriesIncreases[index]:当index是0时,你其实是在找键名为"0"的属性,但你的对象里只有"month1"、"month2"这种键,自然返回undefined,根本拿不到actualIncrease。 - 第二种用
Object.entries的写法:entries返回的是键值对数组,比如["month1", { projectedIncrease: 1.3, ... }],所以increasesArr[index]是一个长度为2的数组,不是你要的月份对象,直接调用.actualIncrease肯定找不到这个属性。
解决方案一:直接构造月份键名(最直接,适合键是month1、month2的固定格式)
因为你的循环index从0开始,对应month1(需要index+1),所以可以直接拼接出对应的键名,然后用方括号访问:
customerNumbers.forEach((amt, index) => { // 把index转成对应的月份键,比如index=0 → "month1" const monthKey = `month${index + 1}`; const actInc = data.sundriesIncreases[monthKey].actualIncrease; console.log(`amt=${amt} index=${index} increase=${actInc}`); });
解决方案二:把对象的值转成数组(适合不确定键名格式的情况)
用Object.values()可以直接提取对象里的所有值(也就是每个月份的嵌套对象),转成一个数组,这样就能用索引直接访问了:
// 把sundriesIncreases的所有值转成数组,顺序和对象的键顺序一致(ES6+规范保证插入顺序) const increasesArr = Object.values(data.sundriesIncreases); customerNumbers.forEach((amt, index) => { // 现在increasesArr[index]就是对应的月份对象 const actInc = increasesArr[index].actualIncrease; console.log(`amt=${amt} index=${index} increase=${actInc}`); });
解决方案三:用Object.entries(需要同时获取键和值时用)
如果你还需要用到month1这种键名,可以用entries,但要记得取键值对数组的第二个元素:
const increasesArr = Object.entries(data.sundriesIncreases); customerNumbers.forEach((amt, index) => { // increasesArr[index]是 [键名, 月份对象],所以取索引1的元素拿到对象 const monthObj = increasesArr[index][1]; const actInc = monthObj.actualIncrease; console.log(`amt=${amt} index=${index} increase=${actInc}`); });
这样应该就能顺利拿到对应索引的月份数据啦~
备注:内容来源于stack exchange,提问作者MeltingDog
相关产品推荐
相关产品推荐

