Javascript: Convert nested JSON to simple JSON
Tags: javascript, json, discuss, webdev
Published: 2022-02-27 13:59:12

This will be the very much used utility function we almost regularly use. 

Depends on the data variety & structuring of data, API response can return much complex JSONs. Sometimes capturing just one field out of whole JSON won't be suffice. We might need to get many fields to show on web page. Traversing such complex JSON wouldn't be a good idea each time. If we can convert that in to simple JSON would be better based on the situation. 

I hope this much introduction is enough. Let's jump into actual stuff.

Here, I am taking much nested JSON. I will convert that into to simple JSON. 

So, here is my example JSON:

```javascript
const obj = {
    first: {
        first: '1',
        second: {
            second: true,
            third: {
                third: 'third',
                fourth: {
                    fourth: 4
                }
            }
        }
    }
}
```

My desired output would be:

```javascript
{first: '1', second: true, third: 'third', fourth: 4}
```

Take a look at input and output once again to get idea.

Let's code something to achieve above:

```javascript
const simpleObj = {};
function destructure(obj) {
    for (let key in obj) {
        const value = obj[key];
        const type = typeof value;
        if (['string', 'boolean'].includes(type) || (type === 'number' && !isNaN(value))) {
            simpleObj[key] = value;
        } else if (type === 'object') {
            Object.assign(simpleObj, destructure(value));
        }
    }
    return simpleObj;
}

console.log(destructure(obj));
```
`for (let key in obj) {` -> Which iterates over given object.

```javascript
const value = obj[key];
const type = typeof value;
```
capturing actual `value` and its `type`.

```javascript
if (['string', 'boolean'].includes(type) || (type === 'number' && !isNaN(value))) {
            simpleObj[key] = obj[key];
```
Validating if the value of key is not an `object`. Copying to `sampleObj` obj if it's not an `object`.

```javascript
else if (typeof obj[key] === 'object') {
            Object.assign(simpleObj, destructure(obj[key]));
        }
```
In case of object, calling the same function again (called `recursion`) to go to nested levels of the object. Also, assigning everything to `sampleObj`. Hence this single object would contain all the key value pairs at the end. 

Lastly, returning that object and printing that to `console`.

I would appreciate suggestions, if we can achieve this in even more best way. Thanks.

<hr style="border-width: 2px;border-color: #87CEEB;">
<h1> 💎 Love to see your response</h1>
<ol>
<li style="padding: 10px;font-size: 30px;"><b>Like</b> - You reached here means. I think, I deserve a like.  </li>
<li style="padding: 10px;font-size: 30px;"><b>Comment</b> - We can learn together. </li>
<li style="padding: 10px;font-size: 30px;"><b>Share</b> - Makes others also find this resource useful.</li>
<li style="padding: 10px;font-size: 30px;"><b>Subscribe / Follow</b> - to stay up to date with my daily articles. </li>
<li style="padding: 10px;font-size: 30px;"><b>Encourage me</b> - <a href="https://www.buymeacoffee.com/urstrulyvishwak" target="_blank">You can buy me a Coffee</a>
</ol>
<hr style="border-width: 2px;border-color: #87CEEB;">

<h2> Let's discuss further. </h2>

<ol style="padding: 20px;">
<li style="padding: 10px;font-size: 30px;">Just DM <br> <a href="https://twitter.com/messages/compose?recipient_id=1388837509824610314&text=Hello world"
class="twitter-dm-button" data-screen-name=“@urstrulyvishwak” data-size="large">@urstrulyvishwak</a>
</li>
<li style="padding: 10px;font-size: 30px;">
<p> Or mention <br> <a href="https://twitter.com/intent/tweet?screen_name=urstrulyvishwak&ref_src=twsrc^tfw" class="twitter-mention-button" data-size="large" data-text="Hi, Vishwak" data-related="@urstrulyvishwak" data-show-count="false">@urstrulyvishwak</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p> </li>
</ol>

<h2> For further updates: </h2>
<a href="https://twitter.com/urstrulyvishwak?ref_src=twsrc^tfw" class="twitter-follow-button" data-size="large" data-text="Hi, Vishwak" data-related="@urstrulyvishwak" data-show-count="false">Follow @urstrulyvishwak</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>