javascript 中的输出对象数组循环

Output object array loop in javascript

我有以下代码。我正在尝试将每个键值("company" 和 "address")输出到不同的 "city1, 2 ,3" 对象(在实际示例中列表不断)。使用 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"
      }
    ]
};

您可以使用 for...in 迭代 data 对象,然后使用 forEach.

迭代内部数组
var body = '';

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

console.log(body);

类似于本的回答。我个人喜欢 javascript 中 foreaches 的普通 for..in 循环,但这是一个偏好。

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

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

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);
  }
}
<ol id="city-list"></ol>