I know that with arrays, only array elements can be added using the .push() method.
My goal is to achieve a similar functionality for objects.
I am familiar with both dot and bracket notation, so this is not a basic question for me. However, I need to do it dynamically in a loop using variables.
I have tried looking into Object.assign() but I couldn't get it to work as intended.
The function below gets called repeatedly. It's essential to normalize the data provided to the function into a mini database using a JavaScript object.
The issue lies in the last line where divContent[section].items[idValue] keeps getting overwritten.
How can I make it so that the record object is "pushed" into the key represented by items[idValue]?
I expect to achieve { itemsKey: { k1:v1, k2:v2, k3:v3 } }. Thank you!
The order of the items does not matter. They should be accessible later on as itemsKey[k1], for instance.
function createItemDb (section, fileName, fileContent) {
var fileExt = fileName.split('.')[1].toLowerCase();
fileType = ((fileExt == 'caption') || (fileExt == 'url')) ? fileExt : 'img';
if (fileType == 'img') {
var regExp = /\((.*?)\)/g;
var matches = regExp.exec(fileName);
fileType = matches[1].toLowerCase();
}
var regRemoveParenIncl = /\([^)]*\)/;
var regRemoveExt = /\.[^\/.]+$/;
var idValue = fileName.replace(regRemoveParenIncl,'').replace(regRemoveExt,'');
record = {};
record[fileType] = fileName;
divContent[section].items[idValue] = record;
}