1

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?

6
  • "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 Commented Aug 11, 2022 at 7:20
  • Lodash has a method for this already... _.set(model, ...string.split(":")). See lodash.com/docs/4.17.15#set Commented Aug 11, 2022 at 7: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 Commented Aug 11, 2022 at 7:24
  • 2
    The expected output is invalid Commented Aug 11, 2022 at 7:25
  • Duplicate of Javascript dotted object keys to object Commented Aug 11, 2022 at 7:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.