Background
I have an object like below:
// Data from the database according to their columns and subordinate tables.
const itemData = {
'license_number': '25/2022',
'application': {
'tracking_number': '535345345',
'applicant_name': 'Misir Ali Humayun'
}
};
I know I can read the data from this object like below:
console.log(itemData.licese_number); // '25/2022'
console.log(itemData.application.tracking_number); // '535345345'
// or
console.log(itemData["licese_number"]); // '25/2022'
console.log(itemData.["application"]["tracking_number"]); // '535345345'
Actual Issue
I want to read the data in a dynamic fashion. For example, I have a defined structure like below:
var placeholder = [
{
"find": "%LICENSE%",
"column": "license_number"
},
{
"find": "%APPLICANT%",
"column": "application.applicant_name"
}
];
Now if I have a replacement function:
const replacePlaceholdersWithData = (content) => {
var replacements = {};
// Constructing the object like { "%STRING%" : "DB_VALUE", "%STRING_2%" : "DB_VALUE_2" }
placeholders.filter((object) => replacements[object.find] = itemData[object.column]); // ISSUE HERE
// @props https://stackoverflow.com/a/7975025/1743124
content = content.replace(/%\w+%/g, function (all) {
return replacements[all] || all;
});
return content;
};
...and a content
like below:
const content = "A License numbered %LICENSE% from the %APPLICANT% is received";
console.log(replacePlaceholdersWithData(content));
// Will output: 'A License numbered 25/2022 from the %APPLICANT% is received'
You can guess that the first placeholder (%LICENSE%
) will be replaced with '25/2022'
, but the second one won't be affected, because of the reading style at : itemData["application.applicant_name"]
won't match with any real column/key.
QUESTION: How can I resolve that issue?
I know I can use object.column.includes('.')
along with object.column.split('.')
and get an array of dimensions. But I am clueless, how can I use the array to get data from a multi-dimensional object dynamically?