I have an extensive JS object with many nested objects, eg:
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
}
I am using a loop to loop through a different data set and I want to use the index of that loop to retrieve the corresponding months data from the array.
However, I am having trouble trying to figure out how to get a given value of the child array by index.
So far I have tried getting it by index as such:
customerNumbers.forEach((amt, index) => {
let actInc = data.sundriesIncreases[index].actualIncrease;
console.log(`amt=${val} index=${index} increase=${actInc}`)
});
And converting the parent object to an array:
var increasesArr = Object.entries(data.sundriesIncreases);
customerNumbers.forEach((amt, index) => {
let actInc = increasesArr[index].actualIncrease;
console.log(`amt=${val} index=${index} increase=${actInc}`)
});
But so far nothing works.
Of course
customerNumbers.forEach((amt, index) => {
if (index == 0) {
let actInc = data.sundriesIncreases.month1.actualIncrease;
console.log(`amt=${val} index=${index} increase=${actInc}`)
}
});
works, but this isn't ideal.
Googling the problem reveals a lot on how to get the key by value noting a lot about how to do the opposite.
Would anyone be able to point me in the right direction?
Since sundriesIncreases is an object with keys like month1, month2, etc., it is not directly indexable like an array. However, you can convert the keys of the object to an array using Object.keys() or Object.entries() and then use the index to retrieve the correct data.
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`);
}
});