0

Hi I have a string in the form:

{"Fruit":"Meat",
     "Vegetable":[
       {"Name":"Author1","Date":"12"},
       {"Name":"Author2","Date":"2"},
       {"Name":"Author3","Date":"14"}
       .
       .
       .
       {"Name": "AuthorN", "Date":"18"}
    ]
} 

that's associated with a JSON/GetNames service.

What's a JavaScript function that can parse and return every "Name" under "Vegetable"?

Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
Xenyal
  • 2,136
  • 2
  • 24
  • 51

2 Answers2

2

With this:

var jsonStr = '{"Fruit":"Meat","Vegetable":[{"Name":"Author1","Date":"12"},{"Name":"Author2","Date":"2"},{"Name":"Author3","Date":"14"}...{"Name": "AuthorN", "Date":"18"}]}';    
var object = JSON.parse(jsonStr),
    names = [];

for (var i = 0; i < object.Vegetable.length; i++) {
    var item = object.Vegetable[i],
        name = item.Name;
    names.push(name);
}
//Finally print the result:
console.log(names);

Or If you just want o print the names (shorter):

var object = JSON.parse(jsonStr);
for (var i = 0; i < object.Vegetable.length; i++)
    console.log(object.Vegetable[i].Name);

Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • If I wanted to print the names so that they can become members of a drop-down menu, how can I do that by using a GET method on the other part of my script? – Xenyal Jan 06 '14 at 19:45
  • The alternative to using a function is by but it's not practical in a scenario with a large number of members. – Xenyal Jan 06 '14 at 19:47
1

Ehh a for loop generally works (once the data has been parsed).

for (var i = 0; i < data.vegetable.length; i++) {
    console.log(data.vegetable[i].name);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157