1

Imagine I have some javascript object eg var person = {};

and I am given a string that represents a dotted traversal into that object eg "Address.Suburb"

and another string that represents the value to be set. eg "Your Town"

What is a general function to enable this to be set. The properties may or may not exist prior to invocation, the function will need to create the properties if necessary.

function MySetter(object, stringTraversal, valueToSet) {
    ....
}

such that

var person = {};

MySetter(person, "Address.Suburb", "CrazyTown")

alert(person.Address.Suburb); // alerts CrazyTown

Thanks.

5 Answers 5

1

Try:

function setObjPath(obj,path,value){
  var parts = path.split('.'), part;

  function error(txt){
      throw new TypeError(txt);
  }

  while (part = parts.shift()){
    if (parts.length){
        obj = part in obj && obj[part] instanceof Object 
              ? obj[part] 
              : part in obj 
                ? error('key ['+part+'] exists but is not an object') 
                : (obj[part] = {}, obj[part]);
    } else {
       obj[part] = value;
    }
  }
}
// usage examples
var person = {name: {prename: {first:'Pete',full:'Pete Michael'}}};

setObjPath(person, 'name.surname.first','Johansen');
alert(person.name.prename.first +' '+person.name.surname.first);
 //=> Pete Johansen

setObjPath(person, 'name.prename.first','George');
alert(person.name.prename.first+' '+person.name.surname.first);
 //=> George Johansen

setObjPath(person, 'name.prename.first.isset',true);
 //=> throws TypeError
Sign up to request clarification or add additional context in comments.

Comments

0

Sorry for the poor naming

function MySetter(obj, path, value){
      var paths = path.split(".");
      var path;
      var ans;
      for(var i in paths) {
                obj = obj[paths[i]];
      };
      return ans;
}

Edit :: I misunderstood the question I think. This returns the value in the string path, and you want to set it?

Comments

0
function MySetter(object, string, value) {
    if (typeof string === 'string') {
        string = string.split('.');
    }

    if (typeof object[string[0]] === 'object')
        return MySetter(object[string[0]], string.slice(1), value);
    else
        return object[string[0]];
}

That should do the trick!

EDIT: Yeah, I misunderstood it, too…

function MySetter(object, string, value) {
    if (typeof string === 'string') {
        string = string.split('.');
    }

    if (string.length === 2) {
        object[string[1]] = value;
    } else {
        return MySetter(object[string[0]], string.slice(1), value);
    }
}

Comments

0

You may try writing your own parser.

function MySetter(object, stringTraversal, valueToSet) {
    var prop = stringTraversal.split('.'),
        len = prop.length,
        obj = object,
        attr = null;
    for (var i = 0; i < len; i++) {
         attr = prop[i];
         if (i == len - 1) {
             obj[attr] = valueToSet;
             return;
         }
         if (!obj[attr] && i < len - 1) {
             obj[attr] = {};
         }
         obj = obj[attr];
    }
}

Something like this (no time to test it).

Comments

0
function MySetter(object, stringTraversal, valueToSet) {
    var pieces = stringTraversal.split('.');

    for(var i in pieces) {
        var val = {};
        if(i == pieces.length-1) {
            val = valueToSet;
        }
        object[pieces[i]] = val;
        object = object[pieces[i]];
    }
}

var person = {};

MySetter(person, "Address.Suburb", "CrazyTown")

alert(person.Address.Suburb); // alerts CrazyTown

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.