I need to create a JSON object as follows:
{
\"app_name\": \"foo\",
\"meta\": {
\"title\": \"foo\",
\"lang\": \"bar\"
},
\"te
You could take an iterative approach by using a default object if a property does not exists.
function setValue(object, key, value) {
var path = key.split('.'),
last = path.pop();
path.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var translations = [{ key: "app_name", val: "foo" }, { key: "meta.title", val: "foo" }, { key: "meta.lang", val: "bar" }, { key: "teaser.foo.headline", val: "foo" }, { key: "teaser.foo.subline", val: "bar" }],
object = {};
translations.forEach(function (o) {
setValue(object, o.key, o.val);
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }