I have an object which already has 3 objects inside it. I want to dynamically add objects to one of those objects inside the original object, and then add key/value pairs to these dynamically added objects.
const result = {
AV: {},
Furnaces: {},
"Production Lines": {}
};
So, this is the existing object with the objects inside. I add key/value pairs dinamically to "AV" easily because its simply
result[AV]["New key"] = value;
But if I try to run through a loop of the furnace names and add key/value pairs to the new object with that furnace's name, like so:
for (let i = 0; i < furnaces.length; i++) {
let furnaceName = furnace[i];
result["Furnaces"][furnaceName]["Raw Material"] = 5;
};
it throws an error
Cannot set property "Raw Material" of undefined to "270000"
you can simply use Object.assign
Assuming you have array of furnaces. Try this,
for (let i = 0; i < furnaces.length; i++) {
let furnaceName = furnaces[i];
const rawMaterial = { 'RawMaterial': 5 }
Object.assign(result.Furnaces, {[`${furnaceName}`]: rawMaterial })
};