1

Very similar to this question: Javascript: how to dynamically create nested objects using object names given by an array

Instead of calling

assign(obj, keyPath, value)

example of usage of the previously answer:

var accountinfo = {}

assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");

That will output:

accountinfo = {name: "", addressinfo: {zipcode:"90210"}};

Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:

assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");

The result would be:

accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}

var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :

assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");

Edit:

Figured it out.

function assign(obj, keyPath, value) {
    keyPath = keyPath.split(‘.’);
    lastKeyIndex = keyPath.length - 1;
    var re = /^(.+?)\[*(\d+)*\]*$/;
    for (var i = 0; i < lastKeyIndex; i++) {
        key = keyPath[i];
        var ind;
        var middle = re.exec(key);
        key = middle[1];
        ind = middle[2];
        if (ind) {
            if (!(obj[key]))
                obj[key] = [];
            if (!(obj[key][ind]))
                obj[key][ind] = {};
        }
        if (!(key in obj))
            obj[key] = {};

        if (ind)
            obj = obj[key][ind];
        else
            obj = obj[key];
    }
    obj[keyPath[lastKeyIndex]] = value;
}
Community
  • 1
  • 1
klinquist
  • 246
  • 1
  • 4
  • 15
  • 2
    Can you explain why you are trying to do this? Why do you need to pass in data in an array like that? While this is possible to do, this approach is pretty non-standard and so I wonder if there might be a better alternative. – Bill Nov 11 '14 at 02:11
  • I agree with Bill. This seems like a bunch of non-standard work to solve a problem that can probably be solved a better way. – jfriend00 Nov 11 '14 at 02:14
  • Bill, what I'm trying to do is create a JSON from a dynamic web page. My on a webpage has a name of "name.address[0].zipcode". With JQuery I can say assign (accountinfo, {{inputName}}, {{inputVal}}). (I'm obviously doing a split by ".") I want to add another address, so I jsut hit a +, the jquery dynamically increments the # so the next input box will have a name of name.address[1].zipcode. – klinquist Nov 11 '14 at 02:17

0 Answers0