1

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.

2

5 Answers 5

2

No need to know the length, you can use forEach

posts.forEach(post => {
    if(post.name.includes("politics")){
        //Doing Stuff
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

you miss a ')' in the if statement
@JohnSneijder You are right (I've copied/pasted the code from the question) It has been corrected. thx
1

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;
});

Comments

0
if(posts.filter(post => post.name.includes("politics")).length > 0){
//Doing Stuff
console.log("One of posts has a name including politics")
}
 

Comments

0

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.

Comments

0

Use the array filter method. Link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.