Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active January 19, 2023 17:35
Show Gist options
  • Save harbirchahal/7eab717d19c656554216bcaa7358e29c to your computer and use it in GitHub Desktop.
Save harbirchahal/7eab717d19c656554216bcaa7358e29c to your computer and use it in GitHub Desktop.
Object utility functions
interface Indexable {
[key: string]: any;
}
function isObject(val: any): boolean {
return Object.prototype.toString.call(val) === "[object Object]";
}
function isObjectLike(val: any): boolean {
return val != null && typeof val === "object";
}
function isObjectEmpty(obj: Indexable): boolean {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
function isNullish(val: any): boolean {
return val === null || val === undefined;
}
/*
* { foo: { bar: "bar", baz: null } } // { foo: { bar: "bar" } }
*/
function removeNullishValues(obj) {
for (const [key, value] of Object.entries(obj)) {
if (isNullish(value)) {
delete obj[key];
} else if (isObject(value)) {
removeNullishValues(value);
}
}
}
/*
* ({ foo: "bar" }, "foo.baz") // undefined
* ({ foo: { bar: "baz" } }, "foo.bar.baz") // undefined
* ({ foo: { bar: "baz" } }, "foo.bar") // baz
* ({ foo: { bar: ["baz"] } }, "foo.bar.0") // baz
* ({ foo: { bar: null } }, "foo.bar") // null
*/
function returnValuePerFieldPath(objOrArr: any, strPath: string): any {
function helper(struct: any, paths: string[]) {
const p = paths.shift();
const v = struct[p];
if (isObjectLike(v) && paths.length) {
return helper(v, paths);
} else if (paths.length) {
return undefined;
} else {
return v;
}
}
return helper(objOrArr, strPath.split("."));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment