I'm having some trouble trying to figure out how to extract the name and url from this Json.
Here's my Json and Javascript. This successfully loops through and extracts each object eg the "1977" portion. But I need to then extract the name and url and display them. Can anyone help? It's so simple I can barely believe I have to ask.
[{
"1977": [{
"name": "my name 1",
"url": "myurl 1"
}],
"2104": [{
"name": "my name 2",
"url": "myurl 2"
}]
}]
var obj = JSON.parse(jsonString); //a parses above json
for (var i = 0; i < obj.length; i++) {
console.log(obj[i]); //returns the object
}
You need to iterate over the objects and pick only the attributes needed, like this
for (var i = 0; i < obj.length; i++) {
for (var year in obj[i]) {
console.log("Current year is", year);
console.log(obj[i][year][0].name);
console.log(obj[i][year][0].url);
}
}
Output
Current year is 1977
my name 1
myurl 1
Current year is 2104
my name 2
myurl 2
for (var i = 0; i < obj.length; i++) {
console.log(obj[i][0].name);
console.log(obj[i][0].url);
}
Here are two ways to access the name.
obj[0]['1977'][0]['name']
obj[0]['1977'][0].name
for (var i = 0; i < obj.length; i++) {
for (var j=0; j<obj[i].length; j++) {
console.log(obj[i][j][0].name);
console.log(obj[i][j][0].url);
}
}
You can simply extract using dot operator
for (var i = 0; i < obj.length; i++) {
var og = obj[i];
Object.keys(og).forEach(function (key) { //missed to loop through it
console.log(og[key][0].name);
console.log(og[key][0].url);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.