Skip to content

Commit

Permalink
fix(getObjectValueByPath): fix getObjectValueByPath (#7543)
Browse files Browse the repository at this point in the history
* fix: getObjectValueByPath can return early if key exists on root object

closes #7302

* fix: switch from checking constructor to typeof
  • Loading branch information
nekosaur authored and dsseng committed Jun 21, 2019
1 parent 953a757 commit 02f5471
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
21 changes: 20 additions & 1 deletion packages/vuetify/src/util/__tests__/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
convertToUnit,
getSlotType,
arrayDiff,
getObjectValueByPath,
} from '../helpers'

describe('helpers', () => {
Expand Down Expand Up @@ -111,6 +112,24 @@ describe('helpers', () => {
expect(deepEqual({ r: [circular] }, { r: [circular] })).toEqual(true)
})

it('should get value directly on object if not undefined', () => {
const obj = {
a: 'foo',
'b.a': 'foobar',
b: {
a: 1,
},
'c.d': undefined,
c: {
d: 'bar',
},
}

expect(getObjectValueByPath(obj, 'a')).toEqual('foo')
expect(getObjectValueByPath(obj, 'b.a')).toEqual('foobar')
expect(getObjectValueByPath(obj, 'c.d')).toEqual('bar')
})

it('should get nested value', () => {
const obj = {
a: {
Expand Down Expand Up @@ -166,7 +185,7 @@ describe('helpers', () => {
expect(getPropertyFromItem(obj, 'c.2.d.x', 'fallback')).toEqual('fallback')
expect(getPropertyFromItem(obj, o => o.a.b + o.c[0])).toEqual(3)
expect(getPropertyFromItem(obj, ['c', 2, 'd'])).toEqual('d')
expect(getPropertyFromItem(obj, 'x.y')).toEqual('nested')
expect(getPropertyFromItem(obj, 'x.y')).toEqual('comp')
expect(getPropertyFromItem(obj, ['x', 'y'])).toEqual('nested')
expect(getPropertyFromItem(obj, ['x.y'])).toEqual('comp')
})
Expand Down
5 changes: 3 additions & 2 deletions packages/vuetify/src/util/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,10 @@ export function deepEqual (a: any, b: any): boolean {
return props.every(p => deepEqual(a[p], b[p]))
}

export function getObjectValueByPath (obj: object, path: string, fallback?: any): any {
export function getObjectValueByPath (obj: any, path: string, fallback?: any): any {
// credit: http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key#comment55278413_6491621
if (!path || path.constructor !== String) return fallback
if (obj == null || !path || typeof path !== 'string') return fallback
if (obj[path] !== undefined) return obj[path]
path = path.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties
path = path.replace(/^\./, '') // strip a leading dot
return getNestedValue(obj, path.split('.'), fallback)
Expand Down

0 comments on commit 02f5471

Please sign in to comment.