Given a strings like 'param1.param2.param3' and a value that should be set on the last parameter, is there a better way than the following to dynamically create an Object and reuse the function to create more parameters on the Object, some which may share a parent parameter? This function also assumes every parameter on the parent Object is an Object with parameters. The purpose is to construct a JSON Object dynamically for a PUT/PATCH request.
function(o,prop,val) { prop = prop.split('.'); prop.forEach(function(property,i){ if(i===0 && typeof(o[property]) === 'undefined'){ o[property] = {}; if(prop.length === 2){ o[prop[0]][prop[1]] = val; } } else if(i===1 && typeof(o[prop[0]][property]) === 'undefined'){ o[prop[0]][property] = {}; if(prop.length === 3){ o[prop[0]][prop[1]][prop[2]] = val; } } else if(i===1 && typeof(o[prop[0]][property]) === 'object'){ if(prop.length === 3){ o[prop[0]][prop[1]][prop[2]] = val; } } else if(i===2 && typeof(o[prop[0]][prop[1]][property]) === 'undefined'){ o[prop[0]][prop[1]][property] = {}; if(prop.length === 4){ o[prop[0]][prop[1]][prop[2]][prop[3]] = val; } } else if(i===2 && typeof(o[prop[0]][prop[1]][property]) === 'object'){ if(prop.length === 4){ o[prop[0]][prop[1]][prop[2]][prop[3]] = val; } } }); return o; };
Here is a Fiddle https://jsfiddle.net/cn25o1vf/
'{ "another": {} }'
), whereas I would have expected it to create a property with the string"object"
, iow:'{ "another": "object" }'
.\$\endgroup\$