0

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?

shaedrich
  • 5,457
  • 3
  • 26
  • 42
  • _"I thought using the isNaN function to know to make it an array"_... sounds like a good idea, did you try it? FYI your example result is not valid JS – Phil Aug 11 '22 at 07:20
  • Lodash has a method for this already... `_.set(model, ...string.split(":"))`. See https://lodash.com/docs/4.17.15#set – Phil Aug 11 '22 at 07:23
  • sure, but I got stuck with what to push to the array, I thought to send in recursive "slots.0.adConfig.ref1" to the function but I couldn't make it work – Atara Zohar Aug 11 '22 at 07:24
  • 2
    The expected output is invalid – adiga Aug 11 '22 at 07:25
  • Duplicate of [Javascript dotted object keys to object](https://stackoverflow.com/q/49302780/283366) – Phil Aug 11 '22 at 07:27
  • `.split` returns an array of strings, so isNaN will always be true. – Layhout Aug 11 '22 at 08:00

0 Answers0