如何在每个新类别后添加<hr />

时间:2019-04-04 08:50:13

标签: javascript html arrays

我有一个称为元素的对象数组,并且这些对象具有两个值(namecategory)。

[
  {name : 'key1', category : 'tech'},
  {name : 'key2', category : 'tech'},
  {name : 'key3', category : 'tech'},
  {name : 'cable1' , category : 'hard'}
  {name : 'cable2' , category : 'hard'}
  {name : 'cable3' , category : 'hard'}
  {name : 'cable4' , category : 'hard'}
]

我想显示所有名称,但是只要到达新的类别

,就添加一个<hr>

请帮助,谢谢您的帮助。

5 个答案:

答案 0 :(得分:1)

我首先要使用Array.prototype.reduce()按类别对对象进行分组,然后使用Array.prototype.map()对每个类别进行迭代:

const data = [
  {name : 'key1', category : 'tech'},
  {name : 'wire1' , category : 'misc'},
  {name : 'key2', category : 'tech'},
  {name : 'cable1' , category : 'hard'},
  {name : 'key3', category : 'tech'},
  {name : 'cable2' , category : 'hard'},
  {name : 'wire2' , category : 'misc'}
];

const dataMap = data.reduce((acc, x) => {
  acc[x.category] = [...(acc[x.category] || []), x];
  return acc;
}, {});

const html = Object.entries(dataMap).map(([cat, items]) => {
  return items.map(item => `<div>${item.name} ${item.category}</div>`).join('');
}).join('<hr>');

document.getElementById('app').innerHTML = html;
<div id="app"></div>

答案 1 :(得分:0)

怎么样?

prev_category = undefined;
elements.forEach(function(e) {
  if (i > 0 && e.category != prev_category) {
    console.log('<hr>');
  }

  prev_category = e.category;
  console.log(e.name);
});

(当然,您可以将console.log()命令替换为您真正想要对这些文本进行的处理,例如将它们附加到一个大字符串上)

答案 2 :(得分:0)

您可以尝试这样的事情,

var category;
$.each(object,function(i,objval)
{
   console.log(objval['name']);
   if(category != "" && category != objval['category'])
   {
     console.log("<hr>");
   }
   category = objval['category'];
});

答案 3 :(得分:0)

迭代对象,并使用模板文字创建dom,并检查数组的索引是否与长度不同,然后添加hr

let elements = [{
    name: 'key',
    category: 'tech'
  },
  {
    name: 'cable',
    category: 'hard'
  }
]
let str = '';

elements.forEach(function(item, index) {
  str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`
  if (index !== elements.length - 1) {
    str += `<hr>`
  }
});
document.getElementById('container').innerHTML = str
<div id='container'></div>

如果您只是在寻找边框,请使用CSS伪选择器

let elements = [{
    name: 'key',
    category: 'tech'
  },
  {
    name: 'cable',
    category: 'hard'
  }
]
let str = '';

elements.forEach(function(item, index) {
  str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`

});
document.getElementById('container').innerHTML = str
.elem:not(:last-child) {
  border-bottom: 1px solid black;
}
<div id='container'></div>

答案 4 :(得分:0)

基本上,您需要先按类别对数据进行排序,然后渲染元素,我以React代码为例

const data = [
  {
    name: "Huawei",
    category: "phone"
  },
  {
    name: "Iphone",
    category: "phone"
  },
  {
    name: "Refacoring Improving the design of existing code",
    category: "book"
  },
  {
    name: "Python Crash Course",
    category: "book"
  },
  {
    name: "My heart will go on",
    category: "music"
  },
  {
    name: "I'm your angel",
    category: "music"
  }
];

function generateCom(data) {
  let listComps = [];
  let category = "";

  // sort the data by category
  data.sort((a, b) => (a.category > b.category ? 1 : -1));

  // generate the component by category
  data.forEach((ele, idx) => {
    if (idx === 0) {
      listComps.push(<h3>{ele.category}</h3>);
      listComps.push(<li>{ele.name}</li>);
      category = ele.category;
      return;
    }

    if (ele.category === category) {
      listComps.push(<li>{ele.name}</li>);
    } else {
      listComps.push(<hr />);
      listComps.push(<h3>{ele.category}</h3>);
      listComps.push(<li>{ele.name} </li>);
      category = ele.category;
    }
  });
  return listComps;
}

可以参考例子 https://codesandbox.io/embed/6x0p7908qw