javascript中的输出对象数组循环

时间:2015-01-14 15:13:13

标签: javascript arrays loops object handlebars.js

我有以下代码。我试图输出每个键值(&#34;公司&#34;和#34;地址&#34;)不同的&#34; city1,2,3&#34;对象(列表在实例中继续)。使用javascript进入<p>。我感到有些失落,因为我尝试了很多不同的方法,但我无法让它发挥作用。我相信这可能是由于结构。如果它只是一个城市就没有问题。

var data = {
  "city1":
    [
      {
        "company": "Ica kvantum",
        "address": "Orrgatan 3-5"
      },
      {
        "company": "Hemköp",
        "address": "Allegatan 26"
      }
    ],
  "city2":
    [
      {
        "company": "Ica Nära",
        "address": "Centrumvägen 7"
      }
    ],
  "city3":
    [
      {
        "company": "Hora brothers kiosk",
        "address": "Rövsgatan 43"
      },
      {
        "company": "Microsoft",
        "address": "Husvägen 38"
      }
    ]
};

3 个答案:

答案 0 :(得分:1)

您可以使用data迭代for...in对象,然后使用forEach迭代内部数组。

var body = '';

for(var city in data) {
    data[city].forEach(function(entry) {
        body += '<p>' + entry.company + ', ' + entry.address + '</p>';
    });
}

console.log(body);

答案 1 :(得分:0)

与Ben的回答相似。我个人喜欢简单地在javascript中循环使用foreaches,但这是一种偏好。

var data = {
  "city1":
    [
      {
        "company": "Ica kvantum",
        "address": "Orrgatan 3-5"
      },
      {
        "company": "Hemköp",
        "address": "Allegatan 26"
      }
    ],
  ...
};

var html = "";
for(var city in data)
{
    //you can append the city to the html here if you want
    // html += "<h2>" + city + "</h2>";
    for(var company in data[city])
    {
        for(var field in data[city][company])
        {
            html += "<p>" + field + ": " + data[city][company][field] + "</p>";
        }
    }
}

答案 2 :(得分:0)

如果在您的产品要求中合理,您可以考虑使用列表元素而不是简单的<p>。尝试使用适当的document.createElement方法而不是构建字符串。类似的东西:

&#13;
&#13;
var data = {
  "city1": [{
    "company": "Ica kvantum",
    "address": "Orrgatan 3-5"
  }, {
    "company": "Hemköp",
    "address": "Allegatan 26"
  }],
  "city2": [{
    "company": "Ica Nära",
    "address": "Centrumvägen 7"
  }],
  "city3": [{
    "company": "Hora brothers kiosk",
    "address": "Rövsgatan 43"
  }, {
    "company": "Microsoft",
    "address": "Husvägen 38"
  }]
};

var cityList = document.getElementById("city-list");
for (var cityName in data) {
  if (data.hasOwnProperty(cityName)) {
    var city = document.createElement("li");

    var cityLabel = document.createElement("p");
    cityLabel.textContent = cityName;
    city.appendChild(cityLabel);

    var companyList = document.createElement("ul");
    city.appendChild(companyList);

    var companies = data[cityName];
    for (var i = 0; i < companies.length; ++i) {
      var company = document.createElement("li");
      company.textContent = companies[i].company + ": " + companies[i].address;
      companyList.appendChild(company);
    }

    cityList.appendChild(city);
  }
}
&#13;
<ol id="city-list"></ol>
&#13;
&#13;
&#13;