我有简单的代码,可以显示基于标签的相关产品,但是我想扩展该代码,可以输入多个标签。目前,我只能运行:

<script type="text/javascript">category('tag1');</script>


而且我得到的每个产品标签中都带有“ tag1”。在这种情况下,name1name2

var products = [
  {
    name: 'name1',
    tags: ['tag1', 'tag2', 'tag3'],
  },
  {
    name: 'name2',
    tags: ['tag1', 'tag3', 'tag4', 'tag5'],
  },
  {
    name: 'name3',
    tags: ['tag2', 'tag5', 'tag6'],
  }

];

var finalHtml = "";

function category(tag) {
  return products.filter(function(product){
    if (~product.tags.indexOf(tag)) {
      finalHtml += '<li>' + product.name + '</li>';
      document.getElementById("related_prod").innerHTML = finalHtml;
    }
  });
}


我期望什么?

当我运行该代码时:

<script type="text/javascript">category('tag1, tag6');</script>


我希望看到每个标签中包含tag1tag2的产品。在这种情况下,它应该是name1name3

最佳答案

这是使用ECMAScript2015的解决方案:



var products = [
  {
    name: 'name1',
    tags: ['tag1', 'tag2', 'tag3'],
  },
  {
    name: 'name2',
    tags: ['tag1', 'tag3', 'tag4', 'tag5'],
  },
  {
    name: 'name3',
    tags: ['tag2', 'tag5', 'tag6'],
  }
];

function category(...tags) {
    let related = document.getElementById("related_prod");
    // clear output
    related.innerHTML = '';
    // turn array values into object properties for faster lookup
    tags = tags.reduce((tags, tag) => (tags[tag] = 1, tags), {});
    // find products that have at least one of the tags
    products.filter(product => product.tags.some(tag => tags[tag]))
            // display the names of the found products
            .forEach(product => {
                let li = document.createElement('li');
                li.textContent = product.name;
                related.appendChild(li);
            });
}

category('tag4','tag5');

<ul id="related_prod"></ul>

关于javascript - 在Javascript中按值从数组中获取元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38211119/

10-12 06:32