基本的javascript检查对象数组

时间:2018-05-22 02:09:57

标签: javascript arrays filter tags mapping

我有对象列表:

tags :[ {item: "#home", active: "true"},
 {item: "#garden", active: "true"},
 {item: "#edible", active: "true"},

]


items : [ 
  { title : "fan", tags:["#engine","#home"]},
  { title : "car", tags:["#heavy","#engine"]},
  { title : "bed", tags:["#home","#wood"]}
]

在javscript中,我试图迭代每个Item,并找出tags对象数组中是否存在任何标记。

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

let tags = [ 
 {item: "#home", active: "true"},
 {item: "#garden", active: "true"},
 {item: "#edible", active: "true"},

]

let items = [ 
  { title : "fan", tags:["#engine","#home"]},
  { title : "car", tags:["#heavy","#engine"]},
  { title : "bed", tags:["#home","#wood"]}
]

items.forEach(item => {
  let found = false;

    tags.forEach(tag => {
    if(item.tags.includes(tag.item)){
        found = true;
      return;
    }
  })

  item.found = found;
});

console.log(items)

循环遍历每个项目,对于每个项目,循环通过标签检查是否存在于item.tags中,如果找到标签,则退出循环并最终将结果分配回项目