Design & Download
Your JS Library
in Seconds!!!

Snippet: put() - Assign A Value To A Path

Written by Christopher West (cwest) on November 09, 2015.
function put(obj, path, value, opt_buildMissingPath) {
  path = typeOf(path, 'String') ? path.split('.') : path;
  
  for (var name, i = 0, e = path.length - 1; (name = path[i], i < e); i++) {
    if (obj[name] == undefined) {
      if (!opt_buildMissingPath) {
        throw new ReferenceError("Path couldn't be followed:  " + slice(path, 0, i + 1).join('.'));
      }
      obj[name] = {};
    }
    obj = obj[name];
  }

  if (e < 0) {
    throw new ReferenceError('Path must be specified.');
  }

  var oldValue = obj[name];
  obj[name] = value;
  return oldValue;
}

put(...) API Documentation

Parameters

  1. obj {Object}:
    Object to be modified.
  2. path {Array|string}:
    Path to the value that should be written. For example to write to `obj.person.name` you would specify `"person.name"` or `["person", "name"]`.
  3. value {*}:
    The value to be assigned.
  4. opt_buildMissingPath {boolean}:
    Optional. Defaults to false. If set to true and the path doesn't already exist it will be created. If set to false and the path doesn't already exist it will not be created and an error will be thrown.

Returns

Returns the previous value at the specified path.