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:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
click below button to copy the code. By JavaScript tutorial team
How could we access the name of the second item in items?
Solution 1:
We can access it this way
data.items[1].name
click below button to copy the code. By JavaScript tutorial team
or
data["items"][1]["name"]
click below button to copy the code. By JavaScript tutorial team
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
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
click below button to copy the code. By JavaScript tutorial team
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
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
click below button to copy the code. By JavaScript tutorial team
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
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
click below button to copy the code. By JavaScript tutorial team
And we know we want to get the first result of the array in the object, perhaps we would like to use
var moe = obj["arr[0].name"];
click below button to copy the code. By JavaScript tutorial team
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.
function flatten(obj){
var root = {};
(function tree(obj, index){
var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
for(var key in obj){
if(!obj.hasOwnProperty(key))continue;
root[index+key+suffix] = obj[key];
if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");
}
})(obj,"");
return root;
}
click below button to copy the code. By JavaScript tutorial team
Now, the complex object can be flattened
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
click below button to copy the code. By JavaScript tutorial team
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:
$..items[1].name
click below button to copy the code. By JavaScript tutorial team
so
var secondName = jsonPath.eval(data, "$..items[1].name");
click below button to copy the code. By JavaScript tutorial team
Solution 5:
We prefer JQuery. It's cleaner and easy to read.
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});