代码之家  ›  专栏  ›  技术社区  ›  MeltingDog

如何检索嵌套的JS对象并通过索引获取其数据?

  •  0
  • MeltingDog  · 技术社区  · 5 月前

    我有一个包含许多嵌套对象的扩展JS对象,例如:

    data = {
      sundriesIncreases : {
        month1: { projectedIncrease: 1.3, actualIncrease: 1.3 },
        month2: { projectedIncrease: 1.6, actualIncrease: 1.5 },
        month3: { projectedIncrease: 1.4, actualIncrease: 1.4 },
        month4: { projectedIncrease: 2, actualIncrease: 2.1 },
        month5: { projectedIncrease: 1.2, actualIncrease: 1.3 },
        //etc
      },
      //etc
    }
    

    我正在使用一个循环遍历不同的数据集,我想使用该循环的索引从数组中检索相应的月份数据。

    然而,我很难弄清楚如何通过索引获取子数组的给定值。

    到目前为止,我一直在尝试按索引获取它:

    customerNumbers.forEach((amt, index) => {
       let actInc = data.sundriesIncreases[index].actualIncrease;
       console.log(`amt=${val} index=${index} increase=${actInc}`)
    });
    

    并将父对象转换为数组:

    var increasesArr = Object.entries(data.sundriesIncreases);
    customerNumbers.forEach((amt, index) => {
       let actInc = increasesArr[index].actualIncrease;
       console.log(`amt=${val} index=${index} increase=${actInc}`)
    });
    

    但到目前为止,一切都不起作用。

    当然

    customerNumbers.forEach((amt, index) => {
       if (index == 0) {
         let actInc = data.sundriesIncreases.month1.actualIncrease;
         console.log(`amt=${val} index=${index} increase=${actInc}`)
       }
    });
    

    有效,但这并不理想。

    在谷歌上搜索这个问题揭示了很多关于如何获得 钥匙 通过 价值 注意到很多关于如何做相反的事情。

    有人能给我指出正确的方向吗?

    1 回复  |  直到 5 月前
        1
  •  1
  •   Akhil Chandran    5 月前

    自从 杂项增加 是一个带有类似键的对象 第1个月、第2个月 等等,它不像数组那样可以直接索引。但是,您可以使用以下命令将对象的键转换为数组 Object.keys() Object.entries() 然后使用 指数 以检索正确的数据。

    const data = {
      sundriesIncreases: {
        month1: { projectedIncrease: 1.3, actualIncrease: 1.3 },
        month2: { projectedIncrease: 1.6, actualIncrease: 1.5 },
        month3: { projectedIncrease: 1.4, actualIncrease: 1.4 },
        month4: { projectedIncrease: 2, actualIncrease: 2.1 },
        month5: { projectedIncrease: 1.2, actualIncrease: 1.3 },
        // etc
      },
    };
    
    const customerNumbers = [100, 200, 300, 400, 500]; // Example data
    
    // Convert the keys of sundriesIncreases to an array
    const increasesArr = Object.values(data.sundriesIncreases);
    
    customerNumbers.forEach((amt, index) => {
      // Ensure the index is within bounds
      if (index < increasesArr.length) {
        const actInc = increasesArr[index].actualIncrease;
        console.log(`amt=${amt} index=${index} increase=${actInc}`);
      } else {
        console.log(`amt=${amt} index=${index} increase=undefined`);
      }
    });