nested-object-to-key-value
Version:
A lightweight utility to flatten nested JavaScript objects into dot-notation key-value pairs and unflatten them back. Perfect for handling complex configurations, form data, or API transformations.
27 lines (26 loc) • 775 B
JavaScript
export function flattenJson(obj, prefix = "") {
const result = [];
function _flatten(currentObj, currentPrefix) {
for (const [key, value] of Object.entries(currentObj)) {
const newKey = currentPrefix ? `${currentPrefix}.${key}` : key;
if (value && typeof value === "object" && !Array.isArray(value)) {
_flatten(value, newKey);
}
else {
result.push({
key: newKey,
value: value,
});
}
}
}
_flatten(obj, prefix);
return result;
}
export function keyValueArrayToObject(obj) {
const result = {};
for (const { key, value } of obj) {
result[key] = value;
}
return result;
}