2

I have an object

 obj = { a: 1, b: { c: 1,  g: x, h: { j: {k: z} } } }; 

if I have an array of dynamic length ["a", "b", [...], "g" ]

How can I now update a.b.c.g ?

example:

function set($target, $new_value, $array){
    //magic
} 

set(obj, y, ['b', 'g']);
// obj is now { a: 1, b: { c: 1, [...] g: **y**, h: { j: {k: z} } } }; 

set(obj, y, ['b', 'h', 'j', 'k']);
// obj is now { a: 1, b: { c: 1, [...] g: y, h: { j: {k: **y**} } } };
1
  • function set($obj, $val, $arr){ for(var i:uint = 0; i < $arr.length-1; i++){ $obj = $obj[$arr[i]]; } $obj[$arr.pop()] = $val; } Commented Jan 30, 2012 at 12:32

1 Answer 1

2
function setObj(target:Object, newValue:Object, path:Array):void {
  for ( var i:uint = 0; i < path.length-1; i++ ) {
    target = target[path[i]];
    if ( target == null ) return;
  }
  target[path[path.length-1]] = newValue;
}

var o:Object = {a: 1, b: { d: 42, e: {f: 7, g: 8}}, c: 3};
trace( o.b.e.f );
setObj(o, "bla", ["b", "e", "f"]);
setObj(o, "42", ["a"]);
trace( o.b.e.f );
trace( o.b.e.g );
trace( o.a );

Copy this code and try to understand how it works. Hope it helped.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.