【问题标题】:Comparing information from an API call and an Array比较来自 API 调用和数组的信息
【发布时间】:2019-03-21 22:36:07
【问题描述】:

我正在尝试将 API 调用的结果与现有数组进行比较。基本上,我想创建一个循环遍历数组的函数,然后循环遍历 API 中的数据以查看是否匹配。

这是我正在使用的数组的一个示例

let array = [ { 
"name": "student1",
"id": 134},
{
"name": "student2",
"id": 135}, 
{
"name": "student3",
"id": 136}
]

这是我在 JavaScript/jQuery 中的函数

function getData() {
$.ajax({
        url: "www.studentapi.com",
        dataType: "json"
    }).done(function(data) {
console.log(data)
}
}

我得到的数据看起来像这样: [ {

"id": 134,
"score": 45},
{ 
"id": 138,
"score": 67},
{ 
"id": 139,
"score": 34}
]

我正在尝试找到一种方法来在数组和数据中找到匹配的 id。到目前为止,我已经尝试过:

for (let j =0; j < data.length; j++) {
    if (array[j]["id"] === data[j].id) {
        console.log("we have a match!")
    }
    else {
        console.log("not a match!");
    }
}

但这不起作用。我在这里做错了吗?

【问题讨论】:

  • 已更正!虽然仍然无法正常工作
  • 通过这种逻辑,您假设每个相应的索引都会带来相同的确切信息。这意味着,假设您在 j=3 中,您假设数据和数组中的索引 j 包含相同的信息。我想您要做的是检查第一个数组中的 ID 是否与第二个数组中的至少一个值匹配(来自 json 请求的值)。
  • 当我尝试它时它正在工作。正如预期的那样,由于135!==138136!==139,第一个对象得到一个we have a match!,另一个对象得到两个not a match。您的解决方案的一个潜在问题是,它仅在对象在两个数组之间的顺序完全相同时才有效。
  • @Benjamin 是的,这就是问题所在,这就是我在上面评论的内容。

标签: javascript jquery json loops match


【解决方案1】:

您可以在数组上使用 find 来查找与某些条件匹配的元素。

下面的逻辑也使用了箭头函数,但可以改为使用普通的function(){}

let array = [
  {
    "name": "student1",
    "id": 134
  },
  {
    "name": "student2",
    "id": 135
  },
  {
    "name": "student3",
    "id": 136
  }
];

let data = [
  {
    "id": 134,
    "score": 45
  },
  {
    "id": 138,
    "score": 67
  },
  {
    "id": 139,
    "score": 34
  }
];

let studentData = array.map(student=>{
  student.data = data.find(record=>record.id === student.id) || {};
  return student;
});

console.log(studentData);

【讨论】:

    【解决方案2】:

    我会使用 javascript 过滤功能。

    let matchingStudents = array.filter(student => {
        return data.find(jsonData => student.id === jsonData.id);
    });
    

    matchingStudents 将保存第一个数组中存在且第二个数组中存在的所有学生。

    如果您想知道语法,这是 ES6。下一代 JavaScript。用旧的 javascript 编写它是:

    var matchingStudents = array.filter(function(student){
         return data.find(function(jsonData){ return student.id === jsonData.id});
    }
    

    【讨论】:

      【解决方案3】:

      专门回答你的问题我在这里做错了吗?

      您在此处的搜索代码假定 arraydata 将以完全相同的顺序包含完全相同的 ID:

      for (let j =0; j < data.length; j++) {
          if (array[j]["id"] === data[j].id) {
      

      根据您提供的示例数据,情况并非如此;您不能总是将 array[j]data[j] 进行比较以匹配 id,因为(例如)您可能需要将 array[4]data[6] 匹配。

      解决这个问题的一种方法是使用嵌套循环:

      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < data.length; j++) {
          if (array[i].id === data[j].id) {
      

      这样,在查找匹配项时,您将比较 array 中的每个条目与 data 中的每个条目。 (这类似于建议 array.mapdata.find 的解决方案正在做的事情,具有一些聪明的提前行为。)

      另一种方法是对两个列表进行排序,然后一起向前推进。

      let array = [
        { "id": 134, "name": "student1" },
        { "id": 139, "name": "student2" },
        { "id": 136, "name": "student3" }
      ];
      
      let data = [
        { "id": 134, "score": 45 },
        { "id": 138, "score": 67 },
        { "id": 139, "score": 34 }
      ];
      
      array.sort((a, b) => a.id - b.id)
      data.sort((a, b) => a.id - b.id)
      let data_i = 0;
      for (let array_i = 0; array_i < array.length; array_i++) {
        while (data[data_i].id < array[array_i].id) {
          data_i++;
        }
      
        if (data_i < data.length && data[data_i].id === array[array_i].id) {
          console.log(`Matched ${array[array_i].name} to score ${data[data_i].score}`);
        } else {
          console.log(`No match found for ${array[array_i].name}`);
        }  
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多