I'm trying to create a JavaScript function that creates an object from a string, but some of my objects need to be arrays. For example, from this string:
"config.content.contents.0.slots.0.adConfig.ref1:hello"
is suppose to be:
{
config: {
content: {
contents: [
{
slots: [
{
adConfig: {
ref1: "hello"
}
}
]
}
]
}
}
}
I found this code that helps but don't handle arrays. Source: Create a JavaScript object from string
var createObject = function (model, name, value) {
var nameParts = name.split("."),
currentObject = model;
for (var i in nameParts) {
var part = nameParts[i];
if (i == nameParts.length - 1) {
currentObject[part] = value;
break;
}
if (typeof currentObject[part] == "undefined") {
currentObject[part] = {};
}
currentObject = currentObject[part];
}
};
and use it like this:
var model = {};
createObject(model, "some.example.here", "hello");
createObject(model, "some.example.there", "hi");
createObject(model, "other.example", "heyo");
I can also have this string:
"config.content.contents.0.slots.1.adConfig.ref1:goodbye"
I thought using the isNaN
function to know to make it an array.
Does anyone have any idea?