按键按对象数组分组循环

时间:2018-11-14 15:26:03

标签: javascript html

这是一个小例子。下面,我列出了{strong>类型的数据groupBygrouped之后,这是我需要帮助的地方。我想像html中那样循环显示每种类型(*您可能需要在运行代码段b / c时查看整页,小预览无法显示全部*)。任何可以帮助我前进的东西,将不胜感激!

  var samples = [
       {id: 1, name: "apple", type: "fruits"},
       {id: 2, name: "zucchini", type: "vegetables"},
       {id: 3, name: "orange", type: "fruits"}
  ];
  function groupBy(data, keyGetter) {
    const map = new Map();
    data.forEach((item) => {
      const key = keyGetter(item);
      const collection = map.get(key);
      if (!collection) {
        map.set(key, [item]);
      } else {
        collection.push(item);
      }
    });
    return map;
  }
  const grouped = groupBy(samples, sample => sample.type);
  console.log("grouped", grouped.get("fruits"));
  //It's unable to show the console log for just const grouped, so I'll attach the screenshot. I was able to see it in the inspect element window under 'console'
  <!--This should be handled dynammically with js-->
  <section>
    <h2>Fruits</h2>
    <div style="background: tomato">
      <div>apple</div>
      <div>orange</div>
    </div>
  </section>
  <section>
    <h2>Vegetables</h2>
    <div style="background: tomato">
      <div>zucchini</div>
    </div>
  </section>

enter image description here

1 个答案:

答案 0 :(得分:1)

说明在代码中为注释

  var samples = [
       {id: 1, name: "apple", type: "fruits"},
       {id: 2, name: "zucchini", type: "vegetables"},
       {id: 3, name: "orange", type: "fruits"}
  ];
  function groupBy(data, keyGetter) {
    const map = new Map();
    data.forEach((item) => {
      const key = keyGetter(item);
      const collection = map.get(key);
      if (!collection) {
        map.set(key, [item]);
      } else {
        collection.push(item);
      }
    });
    return map;
  }
  const grouped = groupBy(samples, sample => sample.type);
  const content = document.getElementById('content');
  
  grouped.forEach((value, key) => {
      const section = document.createElement("section"); //creating section tag
      const h2 = document.createElement("h2"); //creating h2 tag
      const type = document.createTextNode(key.charAt(0).toUpperCase() + key.slice(1)); //creating type name with first latter in upper case e.g Fruits
      const list = document.createElement("div"); // createing div which will contain list of type
      value.forEach(v => { // looping through each type list
        const text = document.createTextNode(v.name); // create name of list element
        list.appendChild(document.createElement("div").appendChild(text)); 
        list.appendChild(document.createElement("br")); //add new line between list elements
      });
      list.style.background = 'tomato';
      h2.appendChild(type);
      section.appendChild(h2);
      section.appendChild(list);
      content.appendChild(section);
  });
  <div id="content">
  </div>