Reputation: 1020
I am trying to access the key and values of my nested array like this:
var obj = $.getJSON("mydata.json", function() {
console.log( "load success" );
});
Object.keys(obj[2].type).forEach(function(key) {
console.log(key, obj[key]);
});
But I get an error.
Here's the structure of the JSON file:
{
"nodes": [
{
"nd": "nd1",
"cat": "cat1"
}
],
"links": [
{
"id": 100
}
],
"types": [
{
"type": "one",
"image": "image001"
},
{
"type": "two",
"image": "image002"
},
{
"type": "three",
"image": "image003"
}
]
}
My goal is to get a list of values of:
one two three
Upvotes: 3
Views: 39660
Reputation: 8280
Here is a functional way to do it in js :
var types = $.getJSON("mydata.json").done(function(response) {
return Object.keys(data["types"]).map(function(element){
return element.type;
}).join(' ');
});
console.log(types);
Upvotes: 0
Reputation: 1235
Something like that?
You have to firstly acces to object.types attribute, then iterate on it to retrieve every type.
var object = {
"nodes": [{
"nd": "nd1",
"cat": "cat1"
}],
"links": [{
"id": 100
}],
"types": [{
"type": "one",
"image": "image001"
}, {
"type": "two",
"image": "image002"
}, {
"type": "three",
"image": "image003"
}]
};
function parseJson(object){
object.types.forEach(function(key) {
console.log(key.type);
});
}
parseJson(object);
--- update to anwer question in comment ---
you could enclose the code in a function, and call it when you load your json:
$.getJSON("mydata.json", function(data) {
parseJson(data);
});
Upvotes: 1
Reputation: 431
You should post the error that you get, but I can tell you that the problem is that your output code executes before the JSON object has been loaded. Try this:
$.getJSON("mydata.json", function(obj) {
console.log( "load success" );
Object.keys(obj[2].type).forEach(function(key) {
console.log(key, obj[key]);
});
});
Upvotes: 1
Reputation: 477
$.getJSON returns a promise because it is asynchronous, but you can set your variable in your callback:
var obj;
$.getJSON("mydata.json", function(data) {
obj = data;
Object.keys(obj[2].type).forEach(function(key) {
console.log(key, obj[key]);
});
});
Upvotes: 1
Reputation: 745
You can do it with this code:
var obj = {
"nodes": [
{
"nd": "nd1",
"cat": "cat1"
}
],
"links": [
{
"id": 100
}
],
"types": [
{
"type": "one",
"image": "image001"
},
{
"type": "two",
"image": "image002"
},
{
"type": "three",
"image": "image003"
}
]
};
Object.keys(obj["types"]).forEach(function(key) {
console.log(obj["types"][key].image);
});
Upvotes: 3
Reputation: 129792
Object.keys(obj[2].type)
doesn't really make sense here. You're not iterating over the properties of any object, you're accessing the same property in a set of objects. This is what map
does.
var types = obj.types.map(x => x.type);
Upvotes: 1