Skip to content

Instantly share code, notes, and snippets.

@timiles
Last active June 6, 2022 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timiles/ebd3d411c738ee5a1e39c00ae3f6b587 to your computer and use it in GitHub Desktop.
Save timiles/ebd3d411c738ee5a1e39c00ae3f6b587 to your computer and use it in GitHub Desktop.
get / set properties using dot notation
// property can have dot notation, eg 'parent.child.value'
export const getPropertyValue = (obj: any, property: string) =>
property.split('.').reduce((a, b) => (a ? a[b] : undefined), obj);
// property can have dot notation, eg 'parent.child.value'
export const setPropertyValue = (obj: any, property: string, value: any) => {
const keys = property.split('.');
const lastKey = keys.pop()!;
let currentObj = obj;
keys.forEach((key) => {
if (currentObj[key] == null) {
currentObj[key] = {};
}
currentObj = currentObj[key];
});
currentObj[lastKey] = value;
};
// objectUtils.test.ts
// import { getPropertyValue, setPropertyValue } from './objectUtils';
describe('object utils: getPropertyValue', () => {
const obj = {
parent: {
child: {
value: 42,
},
},
};
it('returns parent object', () => {
const parent = getPropertyValue(obj, 'parent');
expect(parent).toStrictEqual({ child: { value: 42 } });
});
it('returns child object', () => {
const child = getPropertyValue(obj, 'parent.child');
expect(child).toStrictEqual({ value: 42 });
});
it('returns child.value', () => {
const value = getPropertyValue(obj, 'parent.child.value');
expect(value).toBe(42);
});
it('when property is undefined returns undefined', () => {
const value = getPropertyValue(obj, 'foo.bar');
expect(value).toBeUndefined();
});
});
describe('object utils: setPropertyValue', () => {
const obj = {
parent: {
child: {
value: 42,
},
},
};
it('sets child value', () => {
setPropertyValue(obj, 'parent.child.value', 9000);
expect(obj.parent.child.value).toBe(9000);
});
it('sets new child value', () => {
setPropertyValue(obj, 'parent.child.foo', 9000);
expect((obj as any).parent.child.foo).toBe(9000);
});
it('sets value on undefined', () => {
setPropertyValue(obj, 'foo.bar', 9000);
expect((obj as any).foo.bar).toBe(9000);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment