Reduce a large JSON object down to only what you need
· Reading time: ~3 minute(s) (440 words) programming javascript json webSometimes you need to use an API that returns a large payload, but you may only need to use a small number of fields from that payload. Rather than try storing that data, or hand-balling the data yourself, there is an alternative solution.
In various other languages, such as C#, you can serialise and deserialise data and strip out what data you don’t want (by not declaring those properties in the models). This post explains how you can achieve the same thing in JavaScript with a little help from a pre-defined model, and some recursion:
|
|
So in the above code, you have a function that will do the leg work of iterating over a pre-defined model and building a new object containing only those properties, populated with the matching property data stored in input
.
So what would our model look like?
|
|
So we now know that all we need out of a payload is the properties specified in the example model above, so let’s take a look at our example payload:
|
|
When we call the aforementioned function, providing our data and our model, we get the output with only the properties we want:
|
|
And all should be working fine, and we get the following output:
|
|
Great!
So this will work for every scenario won’t it?
I’m afraid not, this is just a basic example of how you can achieve what you want. This works great if you have (at most) a nested object similar to my example above. If you have arrays etc, things can get messy so you’d need to look into that further. But this is a good starting point that solves most scenarios.