遍历包含数组的对象的数组

时间:2020-05-29 14:24:25

标签: javascript arrays dictionary

 const endpoint =
        'https://raw.githubusercontent.com/FormidableLabs/radon-typeahead/master/demo/car-models.json';
      const cars = [];
      //fetch the data on the cars, convert the json raw into json and the add it to the array cars
      fetch(endpoint)
        .then((blob) => blob.json())
        .then((data) => cars.push(...data));

      function findMatches(wordToMatch, cars) {
        return cars.filter((Carbrand) => {
          //check if the brand matches what was searched
          //create a regular expression
          const regex = new RegExp(wordToMatch, 'gi');
          return Carbrand.brand.match(regex);
        });
      }

      function displayMatches() {
        const matchArray = findMatches(this.value, cars);
        const htmlCars = matchArray
          .map((carBrand) => {
            return `
            <li>${carBrand.brand}</li>
          `;
          })
          .join('');

        const htmlModels = matchArray.map((carBrands) => {
          carBrands.models.map((carModels) => {
            //return carModels + 'this';
            //console.log('li ' + carModels);
            return
            `
            <li>${carModels}</li>
            `;
          });
        });
        console.log('htmlModels ' + htmlModels);
        suggestions.innerHTML = htmlCars + htmlModels;
      }

      const searchInput = document.querySelector('.search');
      const suggestions = document.querySelector('.suggestions');

      searchInput.addEventListener('change', displayMatches);
      searchInput.addEventListener('keyup', displayMatches);
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8" />

    <title>Car filter</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />

    <link rel="stylesheet" href="css/styles.css?v=1.0" />
  </head>
  <style></style>
  <body>
    <form class="search-form">
      <input type="text" class="search" placeholder="City or State" />
      <ul class="suggestions">
        <li>Filter for a car</li>
        <li>or a state</li>
      </ul>
    </form>
    </body>
</html>

我试图遍历由包含键和数组的对象组成的数组。我正在嵌套一个map函数,以显示对象中的数组。我正在尝试在HTML列表<li>

中获取它

这里是对象的示例。

{
    "brand": "Acura",
    "models": [
      "2.2CL",
      "2.3CL",
      "3.0CL",
      "3.2CL",
      "ILX",
      "Integra",
      "Legend",
      "MDX",
      "NSX",
      "RDX",
      "3.5 RL",
      "RL",
      "RSX",
      "SLX",
      "2.5TL",
      "3.2TL",
      "TL",
      "TSX",
      "Vigor",
      "ZDX"
    ]

获得汽车品牌的第一部分起作用,我只是想让它显示阵列中的模型。

如果我console.log'carModels',我可以将模型视为字符串,但是试图返回它们是行不通的。我在控制台中看到,,,,,,

findMatches返回匹配的数组,效果很好。

我要做的是显示汽车品牌的结果,然后在嵌套列表中使用该函数内部的嵌套地图显示该品牌的所有模型。控制台日志记录时它正在工作,但我似乎无法返回结果。

2 个答案:

答案 0 :(得分:0)

像这样吗?

const cars = {
  "ACURA" : [
    "2.2CL",
    "2.3CL",
    "3.0CL",
    "3.2CL",
    "ILX",
    "Integra",
    "Legend",
    "MDX",
    "NSX",
    "RDX",
    "3.5 RL",
    "RL",
    "RSX",
    "SLX",
    "2.5TL",
    "3.2TL",
    "TL",
    "TSX",
    "Vigor",
    "ZDX"
  ],
  BMW : [ 318, 320, 428 ]
}

function displayMatches() {
  let carLI = [];
  let modelLI = [];
  Object.keys(cars)
    .filter(car => car.indexOf(this.value.toUpperCase())===0)
    .forEach(car => { console.log(car)
      carLI.push(`<li>${car}</li>`);
      modelLI = cars[car].map(model => `<li>${model}</li>`);
    })

  document.getElementById("cars").innerHTML=carLI.join("");
  document.getElementById("models").innerHTML=modelLI.join("");
}

window.addEventListener("load",function() {
  document.getElementById("search").addEventListener("input",displayMatches)
})
<input type="text" id="search" autocomplete="off"/>
<ul id="cars"></ul>
<ul id="models"></ul>

答案 1 :(得分:0)

我设法弄对了

const htmlModels = matchArray
  .map((carBrand) => {
    return carBrand.models
      .map((model) => {
        //console.log(model);
        return '<li>' + model + '</li>';
      })
      .join(' ');
  })
  .join(' ');