Last active
May 2, 2019 15:13
-
-
Save brunoguerra/5c08fd2e466d9dca3b7ae9a9128c867d to your computer and use it in GitHub Desktop.
Javascript Select path string from object using modern ecma
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const selectIt = (path, obj) => path && | |
path.split('.').reduce((mem, property) => mem && mem[property], obj) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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