# Flattening JSON with Javascript

**URL:** https://connective.celigo.com/t/flattening-json-with-javascript/122
**Category:** Integrator.io
**Tags:** json, javascript
**Created:** [May 23, 2024, 8:19pm UTC](https://connective.celigo.com/t/flattening-json-with-javascript/122 "2024-05-23T20:19:37Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![jackharris](https://sea1.discourse-cdn.com/flex001/user_avatar/connective.celigo.com/jackharris/32/6618_2.png) [@jackharris](https://connective.celigo.com/u/jackharris)
#### Post date: [May 23, 2024, 8:19pm UTC](https://connective.celigo.com/t/flattening-json-with-javascript/122/1 "2024-05-23T20:19:37Z")

</div>

I have the following code.

```
function postResponseMap (options) {
  const data=options.postResponseMapData[0].data[0].data
  var record=[]
  var key= new Object()

for(let i=0;i\<options.postResponseMapData[0].data[0].data.length;i++){  
//while(i\> options.postResponseMapData[0].data[0].data.length){  
key[options.postResponseMapData[0].data[0].data[i].name] = options.postResponseMapData[0].data[0].data[i].values  
return key  
//return data[i]  
i=i+1  
}

}
```

 ![5301043caa20740200000001-891dcf5278e64e09bd800a825b187928.png](https://us1.discourse-cdn.com/flex001/uploads/celigo/original/2X/2/2c0b49a140a868f0a443d2f83df4c14364b584fe.png)

- The goal
  - I'm trying to flatten the JSON to be Name:Values

- Way I'm attempting to go about it
  - Go through each of the objects in postResponseMapData[0].Data[0].data to find those pieces of information to create a key:value pair

- What doesn't look to be happening. 
  - When I run my code, I only get the first value
  - When I tried returning "i" it doesn't iterate or increment
  - Since it's not iterating/incrementing, I'm only getting the first value

- What I've done so far  

  - I tried to use for(x of y) the area that I needed to look for either wasn't iterable or didn't iterate when it meant to

  1. I tried using a while loop which also didn't iterate and only gave me the first value

- My question
  - What am I doing wrong
  - Is there a better way to accomplish this?

---

<div class="post-metadata">

### Author: ![steveklett](https://avatars.discourse-cdn.com/v4/letter/s/e495f1/32.png) [@steveklett](https://connective.celigo.com/u/steveklett)
#### Post date: [May 23, 2024, 8:37pm UTC](https://connective.celigo.com/t/flattening-json-with-javascript/122/2 "2024-05-23T20:37:46Z")

</div>

```
function postResponseMap (options) {  
 const res = options.postResponseMapData.forEach(l1 =\> {  
 l1.data.forEach(l2 =\> {  
 l2.data.reduce((acc, cur) =\> {  
 acc[cur.name] = cur.values  
 return acc  
 }, {})  
 }  
 }  
}
```

I didn't test that, but that's how I'd do it. Avoid index access like that, even if you know there will only be a single result, it's cleaner (IMO) to make it dynamic as it will also handle empty arrays where index access will fail.
