【问题标题】:How to check if value exist in a json array javascript如何检查值是否存在于json数组javascript中
【发布时间】:2021-01-28 20:55:14
【问题描述】:

我有以下结构:

_id: 'blog',
    posts: [
      {
        _id: 'politics and economy',
        name: 'politics and economy',
        author: 'Mark',
      },
      {
        _id: 'random',
        name: 'random',
        author: 'Michael'
      }
    ]

我的 if 语句

if(posts.name.includes("politics"){
//Doing Stuff
}

我怎样才能让它运行?我不知道数组的长度。

【问题讨论】:

标签: javascript node.js arrays json reactjs


【解决方案1】:

不需要知道长度,可以使用forEach

posts.forEach(post => {
    if(post.name.includes("politics")){
        //Doing Stuff
    }
});

【讨论】:

  • 你在 if 语句中遗漏了一个 ')'
  • @JohnSneijder 你是对的(我已经复制/粘贴了问题中的代码)它已被更正。谢谢
【解决方案2】:

您可以使用method some 来检查其中一个帖子是否具有价值

var name = "politics";
posts.some(singlePost => {
     return singlePost.name == name;
});

【讨论】:

    【解决方案3】:
    if(posts.filter(post => post.name.includes("politics")).length > 0){
    //Doing Stuff
    console.log("One of posts has a name including politics")
    }
     
    

    【讨论】:

      【解决方案4】:

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

      你必须遍历帖子数组。

      【讨论】:

        【解决方案5】:

        使用数组过滤方法。 Link

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-06
          • 1970-01-01
          • 2021-10-10
          • 2018-01-13
          • 2017-03-17
          • 1970-01-01
          • 1970-01-01
          • 2016-09-24
          相关资源
          最近更新 更多