¿Cómo convierto un objeto como la entrada a continuación en salida? En última instancia, quiero convertirlo en un elemento HTML como en el comentario, pero puedo resolverlo a partir de la salida.
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> */Este es un código de trabajo, pero ¿hay una mejor manera de hacerlo?
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);