Set value of a nested object using an array of nested attributes names

An example showing how to set value of a nested object using an array of nested attributes names.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var obj = {
  first: {
    second: {
      third: {
        fourth: 5
      }
    }
  }
};
var set = function(objkeysvalue) {
  var
    last = keys.length - 1,
    object = obj,
    key;
  for (var i = 0; i < last; i++) {
    key = keys[i];
    if (object.hasOwnProperty(key)) {
      object = object[key];
    } else {
      return false;
    }
  }
  key = keys[last];
  if (object.hasOwnProperty(key)) {
    object[key] = value;
    return true;
  }
  return false;
};
set(obj, ['first', 'second', 'third', 'fourth'], 69);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX