-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
  • 183
  • 1
  • 7

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
  • 183
  • 1
  • 7
bvaughn
  • 12,790
  • 42
  • 44