在JS结构中访问数据

时间:2016-11-14 18:06:22

标签: javascript

我试图解析以下数据:

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"}
   ]}
];

使用这些数据我想遍历每个对象并返回其ID,然后返回所有选项。

我知道我需要像这样使用for循环:

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); 
}:

此循环仅返回第一个OptionText&amp; OptionValue来自数据。你能告诉我我做错了什么吗?

感谢。

3 个答案:

答案 0 :(得分:4)

你可以为内部数组使用另一个for循环。

&#13;
&#13;
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); 
    }
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要两个级别的数组才能循环。首先遍历外部数组,然后通过每个项目的选项:

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"}]}];

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

答案 2 :(得分:1)

&#13;
&#13;
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"}
   ]}
];
    
for (var i in data) {
  var id = data[i].id;
  console.log(id)
  for (var opt of data[i].options){
    console.log(opt.value);
    console.log(opt.name)
  }

}
&#13;
&#13;
&#13;

你缺少一个交互循环。另外我相信它可以是你看到用inof

迭代对象和数组的差异(和存在?)的完美例子