JavaScript, Object, Regexp

Retrieves a set of properties indicated by the given selectors from an object.

  • Use for each selector, String.prototype.replace() to replace square brackets with dots.
  • Use String.prototype.split('.') to split each selector.
  • Use Array.prototype.filter() to remove empty values and Array.prototype.reduce() to get the value indicated by each selector.
const get = (from, ...selectors) =>
  [...selectors].map(s =>
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
const obj = {
  selector: { to: { val: 'val to select' } },
  target: [1, 2, { a: 'test' }],
get(obj, '', 'target[0]', 'target[2].a');
// ['val to select', 1, 'test']

Recommended snippets

  • Have you ever wanted to serialize an object but only include certain keys? Turns out JavaScript provides an easy way to do this!

  • pickBy

    JavaScript, Object

    Creates an object composed of the properties the given function returns truthy for.

  • dig

    JavaScript, Object

    Gets the target value in a nested JSON object, based on the given key.