I have to below code. I’m trying to create a grouped object thats groups by phase then by block using key value pairs.
Simplified item:
Item = {
Description: "Description of item",
Value: 199.99,
ValueComplete : 50,
Phase : "Phase 1",
Block : 1,
}
Code snippet:
var result = {};
Items.forEach(item => {
//Phase
var phase = item.Phase ?? 'None';
if (!result[phase]) {
result[phase] = [];
}
//Blocks
var block = item.Block ?? 'None';
if (!result[phase][block]) {
result[phase][block] = []
}
result[phase][block].push(item);
});
Below is the results of the above code. Object is correct at the breakpoint but the phase’s length is 0 so therefor all block information is thrown away.
3
Answers
The issue you’re facing with your code is due to the fact that you are using an array-like syntax to access properties of objects.
Try this please:
You can use
??=
operator to conditionally create missing phase objects and block arrays:The issue you’re facing is because you’re initializing result[phase] as an array ([]), but then you’re trying to use it as an object to store blocks.
To fix this, you should initialize result[phase] as an object ({}) instead of an array.
Here’s the corrected code:
With this change, the result object will have the structure: