javascript - How to assign a value to a field of an object if I ignore their depth in the hierarchy? -
suppose have object this:
obj = { a: { aa: 'aa', ab: 'ab', ac: { aca: 'aca', acb: 'acb' }, b: 'b', set: function obj_set(field, value) { var route = field.split('.'); ... } }
and, can see, have method in object through can assign values object.
obj.set('b', 'b2'); obj.set('a.ab', 'ab2'); obj.set('a.ac.acb', 'acb2');
as don't know how depth assignment be, can't reference field this['b']
, this['a']['ab']
or this['a']['ac']['acb']
. also, in javascript, when assign object variable copied , lose reference original object. then, can't this:
var reference = this; (i = 0, length = route.length; < length; i++) { reference = reference[route[i]]; } reference = value;
how can solve problem? thank you.
you need save last key reference, because last reference primitive value , not object.
var obj = { a: { aa: 'aa', ab: 'ab', ac: { aca: 'aca', acb: 'acb' } }, b: 'b', set: function (field, value) { var route = field.split('.'), key = route.pop(); route.reduce(function (r, k) { r[k] = r[k] || {}; return r[k]; }, this)[key] = value; } }; obj.set('b', 'b2'); obj.set('a.ac.acb', 'acb2'); document.write('<pre>' + json.stringify(obj, 0, 4) + '</pre>');
Comments
Post a Comment