You can use a recursive function to flatten the JSON object and create new keys by concatenating the parent keys with the child keys separated by an underscore. Here's an example implementation:
javascriptfunction flatten(obj, prefix = '') {
return Object.keys(obj).reduce((acc, key) => {
const newKey = prefix ? `${prefix}_${key}` : key;
if (typeof obj[key] === 'object') {
Object.assign(acc, flatten(obj[key], newKey));
} else {
acc[newKey] = obj[key];
}
return acc;
}, {});
}
const json = {
payment: {
id: 1,
amount: 100,
org: { id: 2, name: 'or' }
}
};
const flattened = flatten(json);
console.log(flattened);
// { payment_id: 1, payment_amount: 100, payment_org_id: 2, payment_org_name: 'or' }
The flatten
function takes two parameters: obj
is the JSON object to be flattened, and prefix
is used to keep track of the parent keys. The function returns a new object that has been flattened.
Inside the function, Object.keys
is used to loop through all the keys in the current object. For each key, a new key is created by concatenating the prefix
with the current key using an underscore. If the value of the current key is an object, the flatten
function is called recursively with the current value and the new key as the prefix. Otherwise, the current key-value pair is added to the result object.
The reduce
method is used to accumulate the flattened object, starting with an empty object ({}
). At the end of each iteration, the current key-value pair is added to the accumulated object using Object.assign
.
Finally, we call the flatten
function with the input JSON object and log the resulting flattened object to the console.
Yes, the error you're seeing is likely due to the fact that the flatten
function is being called with null
or undefined
as the obj
parameter. To handle this edge case, you can add a check at the beginning of the function to return an empty object if obj
is falsy.
Here's an updated version of the flatten
function that handles this case:
javascriptfunction flatten(obj, prefix = '') {
if (!obj) {
return {};
}
return Object.keys(obj).reduce((acc, key) => {
const newKey = prefix ? `${prefix}_${key}` : key;
if (typeof obj[key] === 'object') {
Object.assign(acc, flatten(obj[key], newKey));
} else {
acc[newKey] = obj[key];
}
return acc;
}, {});
}
const json = {
payment: {
id: 1,
amount: 100,
org: { id: 2, name: 'or' }
}
};
const flattened = flatten(json);
console.log(flattened); // { payment_id: 1, payment_amount: 100, payment_org_id: 2, payment_org_name: 'or' }
const emptyJson = null;
const flattenedEmpty = flatten(emptyJson);
console.log(flattenedEmpty); // {}
In this updated version, we add a check at the beginning of the flatten
function to see if obj
is falsy (i.e. null
, undefined
, 0
, ''
, etc.). If it is, we return an empty object {}
.
With this check in place, calling flatten(null)
or flatten(undefined)
should now return an empty object instead of causing an error.