-1

I have an object:

{
    messages: {
        foo: {
            bar: "hello"
        },
        other: {
            world: "abc"
        }
    }
}

I need a function:

var result = myFunction('messages.foo.bar'); // hello

How to create this function?

Thanks

McNally Paulo
  • 192
  • 1
  • 8

1 Answers1

1

I've written such a set of utility functions here: https://github.com/forms-js/forms-js/blob/master/source/utils/flatten.ts

There's also the Flat library: https://github.com/hughsk/flat

Either should suit your needs. Essentially it boils down to something like this:

function read(key, object) {
  var keys = key.split(/[\.\[\]]/);

  while (keys.length > 0) {
    var key = keys.shift();

    // Keys after array will be empty
    if (!key) {
      continue;
    }

    // Convert array indices from strings ('0') to integers (0)
    if (key.match(/^[0-9]+$/)) {
      key = parseInt(key);
    }

    // Short-circuit if the path being read doesn't exist
    if (!object.hasOwnProperty(key)) {
      return undefined;
    }

    object = object[key];
  }

  return object;
}
McNally Paulo
  • 192
  • 1
  • 8
bvaughn
  • 13,300
  • 45
  • 46
  • You don't submit a post by hitting "Enter"... – Cerbrus Mar 20 '15 at 17:51
  • I don't know what you're trying to say, or why you're nit picking. – bvaughn Mar 20 '15 at 17:52
  • I'm saying _"Whoops I pressed Enter"_ is a poor excuse to post a link-only answer. – Cerbrus Mar 20 '15 at 17:53
  • That's not what I said. I also had added a *real working code example* by the time you left your original comment, which is why you deleted your first comment. At this point you're being worse than you're accusing me of. Leave off with the drama. I was just trying to help. – bvaughn Mar 20 '15 at 17:55
  • 1
    Ok boys... calm down. Deep breath. Maybe take a walk. ;) – gilly3 Mar 20 '15 at 17:58