Elliott James Elliott James - 23 days ago 8
Javascript Question

Accessing data in JS structure

I'm trying to parse the following data:

data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];


Using this data I want to iterate through each object and return its ID, and then all of it options.

I know I need to use for loop like this:

for (var i =0; i < data.length; i++) {

var id = data[i].id;
var optionText = data[i].options[i].text;
var optionValue = data[i].options[i].value;

console.log(id);
console.log(optionText);
console.log(optionValue);
}:


This loop only returns the first OptionText & OptionValue from the data. Can you teach me what I'm doing wrong?

Thanks.

Answer

You could use another for loop for the inner array.

var data = [{ "id": "orderBy", "options": [{ "value": "order-by=newest&", "name": "newest" }, { "value": "order-by=relevance&", "name": "relevance" }] }, { "id": "searchBy", "options": [{ "value": "search-by=name&", "name": "name" }, { "value": "search-by=number&", "name": "number" }, { "value": "search-by=date&", "name": "date" }, { "value": "search-by=location&", "name": "location" }] }],
    i, j, id, optionText, optionValue;

for (i = 0; i < data.length; i++) {
    id = data[i].id;
    for (j = 0; j < data[i].options.length; j++) {
        optionText = data[i].options[j].name;
        optionValue = data[i].options[j].value;
        console.log(id, optionText, optionValue); 
    }
}