Estoy tratando de escribir una función pero no lo hago. Esta función funciona así.
Entrada: changeSetting("a>b>c","hello")
Después de esa "configuración", el valor con nombre cambia de {} a {"a":{"b":{"c":"hello"}}}
Si la entrada es changeSetting("a","hello") json se convierte en {} a {"a":"hello"}
Mi último intento de código:
function changeSetting(name,val) { if (name.includes(">")) { name = name.split('>') let json = {} name.map((el,i)=>{ let last = "" name.filter(el=>!name.slice(i+1).includes(el)).map(el=> { if(last!="") { json[el] = {} }}) }) } }¿Cómo podemos hacer esto? (La optimización no es importante, pero si es bueno para mí)
const changeSetting = (setting, target) => { if (setting.length < 2) { return { [setting]: target } } else { const keys = setting.split('>'); return keys.reduceRight((acc, curr, i) => { console.log(acc); if(i === keys.length - 1) { return acc = {[curr] : target} } return acc = { [curr]: acc }; }, {}) } } console.log(changeSetting('a', 'hello')); console.log(changeSetting('a>b>c', 'hello'));function changeSetting(inputProperties, value) { let result; const properties = inputProperties.split(">"); result = `{${properties .map((property) => `"${property}":`) .join("{")}"${value}"${"}".repeat(properties.length)}`; return result; } changeSetting("a>b>c", "hello"); changeSetting("a", "hello");Hay varias formas de hacer esto, he comentado el fragmento
const changeSetting = (name, val) => { // Split and reverse the name letters const nameSplit = name.split('>').reverse(); // Set up the inner most object let newObj = {[nameSplit[0]]:val} // Now remove the first letter and recurse through the rest nameSplit.slice(1).forEach((el, idx) => newObj = {[el]: newObj}); console.log(newObj); } changeSetting("a>b>c", "hello") changeSetting("a", "hello") changeSetting("a>b>c>d>e>f>g", "hello")