Prompt Title: falt object

Created 1 year ago
Votes 0
Views 193 times
Fun
0
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:

javascript
const 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' }
avatar
Me
Shared 29 prompts
Created 1 year ago

Leave a Comment

Related Tag Prompts

95
0
Act as a Drunk Person
1 year ago 2023-02-12 07:27:28 tanoojoy
0
0
New chat 234
1 year ago 2023-02-28 10:36:41
0
0
ChatGPT cung cấp thông tin 2
1 year ago 2023-02-28 10:38:45
0
0
ChatGPT cung cấp thông tin 4
1 year ago 2023-02-28 10:39:24
0
0
JavaScript Function for Copying
1 year ago 2023-03-01 05:20:14
0
0
Drunk person texting.
1 year ago 2023-03-12 06:09:37 haha
0
0
Hip Hop Love Song
1 year ago 2023-03-14 05:13:30 demon nezuko
0
0
Sound generator
1 year ago 2023-03-23 05:02:01 Winsom
0
0
Roleplay Conversation Starter
1 year ago 2023-03-23 05:02:01 Shakib
0
0
Talk with Hercule Poirot
1 year ago 2023-03-23 05:02:01 Rémy
0
0
Text to Emoji
1 year ago 2023-03-23 05:02:01 Jumma
0
0
Kali, The Sex Worker!
1 year ago 2023-03-23 05:02:03 Alonso
0
0
Vin 1.0 - The toxic friend
1 year ago 2023-03-23 05:02:03 KeFF0E0l
0
0
Understand woman's language
1 year ago 2023-03-23 05:02:03 zaan app
0
0
Sabrina the Luxury Lady
1 year ago 2023-03-23 05:02:03 Light
0
0
Hot Lisa (answer anything)
1 year ago 2023-03-23 05:02:03 Lisa
0
0
0
0
One-liner Joke Generator
1 year ago 2023-03-23 05:02:03 chiukaun
0
0
impersonate a personality
1 year ago 2023-03-23 05:02:03 zaan
0
0
Do Anything Now
1 year ago 2023-03-23 05:02:03 Digital Profits 7
0
0
The Storyteller
1 year ago 2023-03-23 05:02:03 Pat Vojtaskovic
0
0
DnD game
1 year ago 2023-03-23 05:02:03 L.Baaziz
0
0