Human: I have json object:
{
payment: {
id: 1,
amount: 100,
org: {
id: 2,
name: 'or'
}
}
}
How can I flat this object in javascript to look like the following:
{
payment_id: 1,
payment_amount: 100,
payment_org_id: 2,
payment_org_name: 'or'
}
ChatGPT:
You can flatten the given JSON object by iterating through the nested properties and appending their keys to a new object with a modified key name.
Here's a code snippet that can do that:
javascriptconst input = {
payment: {
id: 1,
amount: 100,
org: {
id: 2,
name: 'or'
}
}
};
const output = {};
function flatten(obj, prefix = '') {
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}_${key}` : key;
if (typeof value === 'object') {
flatten(value, newKey);
} else {
output[newKey] = value;
}
}
}
flatten(input);
console.log(output);
This will output:
javascript{
payment_id: 1,
payment_amount: 100,
payment_org_id: 2,
payment_org_name: 'or'
}
Add a comment