javascript tutorial - [Solved-5 Solutions] Access/process objects,arrays or JSON - javascript - java script - javascript array
Problem:
We have a (nested) data structure containing objects and arrays. How can We extract the information, i.e. access a specific or multiple values (or keys)? For example:
How could we access the name of the second item in items?
Solution 1:
We can access it this way
or
Solution 2:
In case you're trying to access an item from the example structure by id or name, without knowing it's position in the array, the easiest way to do it would be to use underscore.js
From my experience, using higher order functions instead of for or for..in loops results in code that is easier to reason about, and hence more maintainable. Just my 2 cents.
Solution 3:
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use. If the property being accessed is already known, but the path is complex, for example in this object
And we know we want to get the first result of the array in the object, perhaps we would like to use
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
Now, the complex object can be flattened
Solution 4:
Using JSONPath would be one of the most flexible solutions if we are willing to include a library:https://github.com/s3u/JSONPath (node and browser) For our use case the json path would be:
so
Solution 5:
We prefer JQuery. It's cleaner and easy to read.