0

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.

John Sneijder
  • 159
  • 1
  • 2
  • 12
  • 1
    You can use the array filter method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter to get the items from the array that match your criteria. – szczocik Oct 14 '20 at 12:45
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – JK. Oct 15 '20 at 22:55

5 Answers5

1

No need to know the length, you can use forEach

posts.forEach(post => {
    if(post.name.includes("politics")){
        //Doing Stuff
    }
});
Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15
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;
});
Blu
  • 4,036
  • 6
  • 38
  • 65
0

Use the array filter method. Link

Blu
  • 4,036
  • 6
  • 38
  • 65
0
if(posts.filter(post => post.name.includes("politics")).length > 0){
//Doing Stuff
console.log("One of posts has a name including politics")
}
 
NinjaDev
  • 402
  • 2
  • 6
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.

Dipankar Maikap
  • 447
  • 4
  • 13