How do I convert an object like the input below to output? Ultimately I want to convert it to an HTML element like in the comment but I can figure it out from output.
var input = {
"attributes.src": "https://google.com/search",
"attributes.src.q": "test",
"attributes.src.ei": "abc",
"attributes.type": "text/javascript",
tag: "meta",
};
var output = {
"attributes.src": "https://google.com/search?q=test&ei=abc",
"attributes.type": "text/javascript",
tag: "meta",
}
/* <meta src="https://google.com/search?q=test&ei=abc" type="text/javascript"></meta> */
This is working code but is there a better way to do this?
var data = {
"attributes.src": "https://google.com/search",
"attributes.src.q": "test",
"attributes.src.ei": "abc",
"attributes.type": "text/javascript",
"tag": "meta",
};
{/* <meta src="https://google.com/search?q=test&ei=abc" type="text/javascript"></meta> */}
function setValue(object, path, value) {
var keys = path.split(".");
var last = keys.pop();
var existing = keys.reduce((o, k) => (o[k] = o[k] || {}), object);
if (typeof existing === "string") {
var url = new URL(existing);
url.searchParams.append(last, value);
last = keys.pop();
var existingParent = keys.reduce((o, k) => (o[k] = o[k] || {}), object);
existingParent[last] = url.href;
} else {
existing[last] = value;
}
return object;
}
var target = Object.entries(data).reduce((o, [k, v]) => setValue(o, k, v), {});
console.log(target);