setObjectPropertyByPath

Working on function to set an objects properties based on path given

by WizKid81

JavaScript

//console.clear();
//Accepts an object and string path.  Will return the attribute defined by the path from the
///object.  The path would be in the format of array[index].property
function setObjectPropertyByPath(object, path, value) {
    path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    path = path.replace(/^\./, '');           // strip a leading dot
    var a = path.split('.');
  
  var currentObject;
  /* console.log(path);
  console.log(a) */
  
  currentObject = object;
  
for (var i = 0; i < a.length; i++)
{
//console.log("loop " + i + ":");
	if (currentObject.hasOwnProperty(a[i]) === false) {
  	console.log("Creating property " + a[i] + " in:" );
    console.log(JSON.parse(JSON.stringify(currentObject)));
  	//Object.defineProperty(currentObject, a[i], {value: {}, writable: true});
    currentObject[a[i]] = {};
  }

  ///currentObject = currentObject[a[i]];
  
  if (i === a.length - 1) {
  	console.log("Setting value to " + value + " for property '" + a[i] + "'");
    currentObject[a[i]] = value;
    console.log(JSON.parse(JSON.stringify(currentObject)));
  }
  else {
  	currentObject = currentObject[a[i]];  
  }
}
}


/* var x = {}; //{abilities: [{currentTier: 1}]};

x.levelOne = {};
x.levelOne.propertyOne = {};
x.levelOne.propertyOne.valueOne = "prop1";
x.levelOne.propertyTwo = {};
x.levelOne.propertyTwo.attributeOne = "att1";

//console.log(object.hasOwnProperty("propertyTwo"));

console.log(JSON.parse(JSON.stringify(x)));
//setObjectPropertyByPath(x, "levelOne.propertyOne.valueOne", "prop1");
//setObjectPropertyByPath(x, "levelOne.propertyTwo.attributeOne", 'att1');
setObjectPropertyByPath(x, "levelOne.propertyTwo.attributeTwo", 'att2');

//setObjectPropertyByPath(x, "abilities[0].currentTier", "current Tier");
//setObjectPropertyByPath(x, "stats.final.Health", "my Health");

console.log(JSON.parse(JSON.stringify(x)));
 */
var Roster = [];
Roster[0] = {MAGMATROOPER: [{updated: 123456789, player: "COMANDER", level:...