javascript - jQuery Ajax每个函数检查返回ID是否与前一个相同

标签 javascript jquery json loops each

我正在使用 AJAX 从删除服务器获取数据,然后使用 every 进行循环。

现在我想做的是如果返回值数据与之前的相同我就做一些事情 我有 10 val.userId == 1 ,我只想做一次而不是 10 次。

在实际情况下我不知道用户ID我想让它动态怎么样 Fox示例用户12123有10次,用户1239823有1000次

例如这里 https://jsonplaceholder.typicode.com/posts

$(document).ready(function(){
        getData();
      });


function getData(){
    $.ajax({
          type: "GET",
          url: "https://jsonplaceholder.typicode.com/posts",
          dataType: 'json',
          success: function(response){

              $.each(response, function(index, val) {
                console.log(val); // get all return data
                // as we can see userId == 1 have 10 posts , I just want to console.log only once if usdId == 1
                if(val.userId == 1){
                  console.log(val.userId);  // this one consoloe .log 10 times since we have 10 userId 
                }
                // how about in the real case I do not know the user ID i wanna make it dynamic
                // fox example user 12123  has 10 times ,  user 1239823 has 1000 times 

              });


          },
          error: function(xhr, textStatus, error){console.log(xhr.statusText);console.log(textStatus);console.log(error);

          }
    });
  }

感谢您的阅读

最佳答案

如果您想根据userId删除重复的项目,您可以使用响应进行循环并过滤它们。

$(document).ready(function(){
    getData();
});


function getData(){
    $.ajax({
          type: "GET",
          url: "https://jsonplaceholder.typicode.com/posts",
          dataType: 'json',
          success: function(response){
              var arr = [];
              
              response.forEach(function (item) {
                var result = arr.find(x => x.userId === item.userId);
                if (!result) {
                  arr.push(item);
                }
              });
              
              console.log(arr);
          },
          error: function(xhr, textStatus, error){            
              console.log(xhr.statusText);
              console.log(textStatus);
              console.log(error);
          }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - jQuery Ajax每个函数检查返回ID是否与前一个相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60144829/

相关文章:

javascript - 使用javascript将两个图像加载到html

javascript - FF本地如何处理sessionStorage(测试用)

java - 安卓 : How to get JSON object keys from this json:

ios - 如何在iOS中解析这种json字符串

javascript - JSON 用默认字符串替换所有空值

javascript - Sails.js - Postgresql 适配器多模式

javascript - jquery jquery-1.9.0 设置div显示:none when I trying to use toggle

javascript - 如何通过按按钮导航 html 表格(带有 tbody)单元格?

jQuery UI 可选择的 css 转换问题

c# - 返回 NULL 值的 JSON 反序列化器