Chilian Chilian - 11 months ago 44
Javascript Question

JS – How to build a dynamic nested object of arrays with objects etc. from string

This is a nice evening project, but actually i'm stuck with some headache.

All I need is a function like this example:

result = set("itemCategories[0].items[0].name", "Test")


which should return:

{ itemCategories: [
{
items: [ {name: "Test"} ]
}
}]


...and in case of the given attribute "itemCategories[1].items[2].name" this result:

{ itemCategories: [
null,
{
items: [
null,
null,
{name: "Test"}
]
}
}]

Answer Source

Use lodash#set:

result = lodash.set({}, "itemCategories[0].items[0].name", "Test")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download