I have a replace function that takes the values from an object and replaces the template literals like this:
let componentJSON = [
{ "template": "<div class='${layout} ${border}'></div>" },
{
"layout": "grid",
"color": "blue",
"border": "primary"
}
];
const template = componentJSON[0].template
const classes = componentJSON[1]
let html = template.replace(/\$\{(.*?)\}/g, (match, key) => classes[key]);
console.log(html);
Is it possible to then return (or consoleLog) the object key that wasn't used? In this case "color": "blue"
I suppose you could delete the property from the object, then examine what remains in the object at the end.
let componentJSON = [
{ "template": "<div class='${layout} ${border}'></div>" },
{
"layout": "grid",
"color": "blue",
"border": "primary"
}
];
const template = componentJSON[0].template
const classes = componentJSON[1]
const html = template.replace(
/\$\{(.*?)\}/g,
(match, key) => {
const str = classes[key];
delete classes[key];
return str;
}
);
console.log(componentJSON[1]);
Keep track of the keys used then filter them from the original key set
let componentJSON = [
{ "template": "<div class='${layout} ${border}'></div>" },
{
"layout": "grid",
"color": "blue",
"border": "primary"
}
];
const [ { template }, classes ] = componentJSON;
const usedKeys = new Set();
let html = template.replace(/\$\{(.*?)\}/g, (match, key) =>
(usedKeys.add(key), classes[key]));
console.log(html);
const unused = Object.fromEntries(
Object.entries(classes).filter(([ key ]) => !usedKeys.has(key))
);
console.log("unused", unused);