nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
36 lines (35 loc) • 1.07 kB
JavaScript
import { isNotEmptyObject } from '../guards/non-primitives.js';
import { stableStringify } from '../utils/index.js';
export function cloneObject(obj, serialize = false) {
try {
if (!serialize && typeof structuredClone === 'function') {
return structuredClone(obj);
}
return JSON.parse(stableStringify(obj));
}
catch {
return { ...obj };
}
}
export function countObjectFields(obj) {
if (obj != null)
return Object.keys(obj)?.length;
return 0;
}
export function extractObjectKeys(obj, _tuple) {
const keys = isNotEmptyObject(obj) ? Object.keys(obj) : [];
return keys;
}
export function extractObjectKeysDeep(obj) {
function _getDeepKeys(candidate) {
let result = [];
for (const key in candidate) {
result.push(key);
if (isNotEmptyObject(candidate[key])) {
result = [...result, ..._getDeepKeys(candidate[key])];
}
}
return result;
}
return (isNotEmptyObject(obj) ? _getDeepKeys(obj) : []);
}