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

PHOTO EMBED

Sat Feb 26 2022 02:20:27 GMT+0000 (UTC)

Saved by @mboljar

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };

// Example
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']
content_copyCOPY

https://madza.hashnode.dev/24-modern-es6-code-snippets-to-solve-practical-js-problems?guid