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.
var obj = {
  first: {
    second: {
      third: {
        fourth: 5
      }
    }
  }
};

var set = function(obj, keys, value) {
  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);

Responses

0 Replies