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(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
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
var name = "politics";
posts.some(singlePost => {
return singlePost.name == name;
});
Use the array filter method. Link
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.