[英]How to check if value exist in a json array javascript
I have the following Structure:我有以下结构:
_id: 'blog',
posts: [
{
_id: 'politics and economy',
name: 'politics and economy',
author: 'Mark',
},
{
_id: 'random',
name: 'random',
author: 'Michael'
}
]
My if Statement :我的 if 声明:
if(posts.name.includes("politics"){
//Doing Stuff
}
How Can I get this running?我怎样才能让它运行? I do not know the length of the Array.
我不知道数组的长度。
No need to know the length, you can use forEach
不需要知道长度,你可以使用
forEach
posts.forEach(post => {
if(post.name.includes("politics")){
//Doing Stuff
}
});
You can use the method some to check if one of the posts has the value您可以使用some 方法检查其中一个帖子是否具有该值
var name = "politics";
posts.some(singlePost => {
return singlePost.name == name;
});
if(posts.filter(post => post.name.includes("politics")).length > 0){
//Doing Stuff
console.log("One of posts has a name including politics")
}
const posts = [ { _id: 'politics and economy', name: 'politics and economy', author: 'Mark' }, { _id: 'random', name: 'random', author: 'Michael' } ] posts.forEach(post => { if(post.name.includes("politics")){ //Do Your Stuff console.log(post.name) } });
You have to loop through the posts array.您必须遍历posts 数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.