Right, all the uses of eval were unnecessary.

I came up with a quick utility along these lines, that allows you to pass in
an object like:

{"a.b.c": 1, "a.b.d":2, "a.b.e[0].f": 3, "a.b.e[1].g": 4}

Which you might get from a Prototype form utility function, and get back an
exploded object like:

{"a": {"b": {"c":1, "d":2, "e": [{"f": 3}, {"g": 4}]}}}

Which is suitable for passing to Object.toJSON().  It basically just handles
intermediate objects that can be ordinary values or arrays, but that handles
all the cases I can think of.  Let me know what you think.

  function to_exploded_object(object) {
    var root = {};

    $H(object).each(function(property) {
      var current = root,
          path = property.key.split("."),
          last = path.pop();

      function set_and_advance_key(key, value) {
        var match = key.match(/^(\w+)(?:\[(\d+)\])?/),
            name = match[1],
            index = match[2];

        if (index) {
          index = parseInt(index);
          current[name] = current[name] || [];
          current[name][index] = current[name][index] || value;
          current = current[name][index];
        } else {
          current[name] = current[name] || value;
          current = current[name];
        }
      }

      path.each(function(key) { set_and_advance_key(key, {}); });
      set_and_advance_key(last, property.value);
    });

    return root;
  }

-Fred

On Wed, Jun 11, 2008 at 4:43 PM, kangax <[EMAIL PROTECTED]> wrote:

>
> Fair enough, but still makes little sense to use eval:
>
> function toObject(str) {
>  var result = { };
>  str.split('.').inject(result, function(parent, child) {
>    return parent[child] = parent[child] || { };
>  });
>  return result;
> };
>
> toObject('foo.bar.baz'); // { foo: { bar: baz: { }}}


-- 
Science answers questions; philosophy questions answers.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Spinoffs" group.
To post to this group, send email to rubyonrails-spinoffs@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to