var test = {
foo: {
bar: {
test: {
prop: 'someProp123'
}
}
}
};
objectPath(test, 'foo.bar.test.prop'); //> "someProp123"
objectPath(test, 'foo.bar.test'); //> { prop: "someProp123" }
function objectPath(object, key, value) {
var path = key.split('.');
var get = function (collection, start) {
return collection.reduce(function (previous, current) {
return previous[current];
}, start);
};
if (value) {
var way = path.pop();
get(path, object)[way] = value;
return object;
} else {
return get(path, object);
}
}
Источник