0

I need to convert an object with cannonical properties into object with nested properties, splited by '.'

Example:
From:

obj['a.b.c'] = 123;

to:

obj.a.b.c = 123;

Any elegant solutions?

Or maybe there is a solution in ExtJS to make form.getValues() to return an array of fields grouped by names like fieldname[1] or fieldname.1?

Tiago Sippert
  • 1,324
  • 7
  • 24
  • 33
4orever
  • 105
  • 6
  • So you have a string that has `a.b.c` that you want to use as a object property lookup, or does your code currently assigns properties like `obj['a.b.c']`, but you want to assign properties with `obj.a.b.c`? I'm extremely confused. – Qantas 94 Heavy May 30 '13 at 12:46
  • @Quentin I was just looking for that very same question, as I remember writing the accepted answer for it :) – Alnitak May 30 '13 at 12:51

1 Answers1

1

Have a look at the private method in ClassManager "createNamespaces". It's essentially what you need to do, except root shouldn't default to global, it should default to your object:

function setValue(o, key, value) {
    var root = o,
        parts = key.split('.'),
        ln = parts.length,
        part, i;

    for (i = 0; i < ln; i++) {
        part = parts[i];

        if (typeof part != 'string') {
            root = part;
        } else {
            if (!root[part]) { 
                root[part] = (i === ln - 1) ? value : {};
            }

            root = root[part];
        }
    }
}

var o = {};
setValue(o, 'a.b.c', 123);
console.log(o.a.b.c);
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66