在Javascript中按值从数组中获取元素

时间:2016-07-05 19:23:16

标签: javascript json

我有简单的代码,允许我根据标签显示相关产品,但我想扩展该代码,我可以输入多个标签。此刻我只能跑:

<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

2 个答案:

答案 0 :(得分:1)

这可能是一般的,因为我从你的要求中理解你想要“或”不是“和”所以答案可以是:

function category() {
  var args = Array.prototype.slice.call(arguments);
  return products.filter(function(product){
    args.forEach(function(arg){   
     if (product.tags.indexOf(arg)> -1) {// readability 
       finalHtml += '<li>' + product.name + '</li>';
       document.getElementById("related_prod").innerHTML = finalHtml;
     }
  })
  });
}

编辑:为了获得更好的分离和可读的解决方案(假设您使用的是ecmascript5垫片)

function findProducts(){
    var args = Array.prototype.slice.call(arguments);
    var foundProducts = [];
    products.forEach(function(product) {
         args.forEach(function(arg){  
            if(product.tags.indexOf(arg) > -1 && foundProdutcs.indexOf(product) == -1)
                foundProducts.push(product);
         }
    });
    return foundProducts;

}
function doSomethingWithTheProducts() {
   var products = findProducts.apply(this,arguments);
   var finalHtml = "";
   products.forEach(function(product){
       finalHtml += "<li>" + product.name + "</li">;
   });
   document.getElementById("related_prod").innerHTML = finalHtml;
}

doSomethingWithTheProducts('tag1','tag2');

答案 1 :(得分:1)

以下是使用ECMAScript2015的解决方案:

&#13;
&#13;
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');
&#13;
<ul id="related_prod"></ul>
&#13;
&#13;
&#13;