我正在使用以下代码过滤对象数组:
filterCategory(category: [string]) {
this.projects = this.projects.filter(project => project.category == category);
}
它在某种程度上有效,但我想对它进行优化,以便返回任何具有类别字符串的对象。
e.g。
project: [{
name: "thing1"
category: ["Design", "Web Design"]
}, {
name: "thing2"
category: ["Web Design"]
}, {
name: "thing3"
category: ["Design"]
}, {
name: "thing4"
category: ["Design", "Web Design"]
}]
filterCategory("Design")
filterCategory设计目前只返回thing3但我希望它返回thing1,thing3和thing4。
答案 0 :(得分:2)
JavaScript的Array.indexOf将查看匹配的每个数组值。
project => project.category.indexOf(category) !== -1
答案 1 :(得分:1)
tol = 0.001
df['is_it_whole'] = ((df['value'].round() - df['value']).abs() < tol)
答案 2 :(得分:0)
我找到了另一种(代码较少)的方法来使用ES6。您可以使用 .includes 代替project => project.category.indexOf(category) !== -1
来执行相同的操作,以便最终代码如下所示:
project => project.category.includes(category)
如果您正在使用ES6,那么对我来说也是一样的清洁工作。