I am new to java script , so my apologies if this is trivial. My question is syntactical, if I have an object:
this.state = {
A : {
B: {
You could split the path and reduce the object.
function getValue(o, path) {
return path.replace(/\[/g, '.').replace(/\]/g, '').split('.').reduce(function (o, k) {
return (o || {})[k];
}, o);
}
var o = { A : { B: { C: [{ value: 'Brenda' }, { value: 'Jim' }, { value: 'Lucy' }] } }};
console.log(getValue(o, 'A.B.C[1]').value); // Jim
console.log(getValue(o, 'A.B.C[0].value')); // Brenda
console.log(getValue(o, 'Z[0].Y.X[42]')); // undefined
For setting a value, you could split the path and reduce the path by walking the given object. If no object exist, create a new property with the name, or an array. Later assign the value.
function setValue(object, path, value) {
var way = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'),
last = way.pop();
way.reduce(function (o, k, i, kk) {
return o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {});
}, object)[last] = value;
}
var test = {};
setValue(test, "foo.name", "Mr. Foo");
setValue(test, "foo.data[0].bar", 100);
setValue(test, "and.another[2].deep", 20);
console.log(test);