Skip to content

Instantly share code, notes, and snippets.

@brunoguerra
Last active May 2, 2019 15:13
Show Gist options
  • Save brunoguerra/5c08fd2e466d9dca3b7ae9a9128c867d to your computer and use it in GitHub Desktop.
Save brunoguerra/5c08fd2e466d9dca3b7ae9a9128c867d to your computer and use it in GitHub Desktop.
Javascript Select path string from object using modern ecma
export const selectIt = (path, obj) => path &&
path.split('.').reduce((mem, property) => mem && mem[property], obj)
import { selectIt } from './functional'
test('object member selection', () => {
const data = {one: { number: 1 }, two: 2, three: [1,2,{ mixed: true}] };
expect(selectIt('two', data)).toBe(2)
expect(selectIt('one.number', data)).toBe(1)
expect(selectIt('three.2.mixed', data)).toBeTruthy();
});
test('array member selection', () => {
const arr = { array: [1,2,3,{ok: true}] }
expect(selectIt('array.3.ok', arr)).toBeTruthy();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment