简体   繁体   English

如何避免每次执行排序、过滤等操作时都发出 fetch() 请求。香草 JavaScript 中的一些 JSON 数据?

[英]How to avoid making a fetch() request every time you do something like sort, filter, etc. some JSON data in vanilla JavaScript?

When the page loads it brings data to the page good:当页面加载时,它会将数据带到页面:

fetch("theData.json")
  .then(function (response) {
    return response.json();
  })
  .then(function (objArray) {
    mainFunctionThatPresentsTheData(objArray);
  });

But then I have multiple buttons that do sorting, for example lowest to highest price, highest to lowest based on some attribute of the json objects in the JSON Array, etc.但后来我有多个按钮进行排序,例如从最低到最高价格,从最高到最低基于 JSON 数组中 JSON 对象的某些属性等。

I managed to successfully perform this functionality, however, I don't think it's really efficient because I make a new fetch() request every time I click a "sort" button:我设法成功地执行了这个功能,但是,我认为它不是很有效,因为每次单击“排序”按钮时我都会发出一个新的 fetch() 请求:

function customSort(sortOrder, byWhatAttribute) {
  output.innerHTML = "";
  fetch("theData.json")
    .then(function (response) {
      return response.json();
    })
    .then(function (objArray) {
      for (let i = 0; i < obj.length; i++) {
        objArray[i].somethingInTheJsonObjArrayThatIWantToSort.sort(sortOrder(byWhatAttribute));   
      }
      mainFunctionThatPresentsTheData(objArray);
    });
}

I tried this:我试过这个:

let globalEmptyArray; //<----- addition 1
//this gets called when the page loads or gets refreshed
fetch("theData.json")
  .then(function (response) {
    return response.json();
  })
  .then(function (objArray) {
  globalEmptyArray = objArray; //<----- addition 2
    mainFunctionThatPresentsTheData(objArray);
  });

function customSort(sortOrder, byWhatAttribute) {
  output.innerHTML = "";
  // addition 3 ... the globalEmptyArray is not supposed to be empty anymore.
  for (let i = 0; i < globalEmptyArray.length; i++) {
    globalEmptyArray[i].somethingInTheJsonObjArrayThatIWantToSort.sort(sortOrder(byWhatAttribute));
    
  }

  mainFunctionThatPresentsTheData(globalEmptyArray);
}

The customSort() function gets called like this: customSort() function 被这样调用:

sortBySomethingAscendingButton.addEventListener("click", () => {
  customSort(sortAscendingBy, "someAttribute");
});

This actually does work but the problem is that it only works once, like, when I do "sortDescendingBy":这确实有效,但问题是它只有效一次,比如,当我执行“sortDescendingBy”时:

sortBySomethingDescendingButton.addEventListener("click", () => {
  customSort(sortDescendingBy, "someAttribute");
});

It gives the same result as customSort(sortAscendingBy, "someAttribute")... like the data is "stuck" in ascending order just because I clicked the ascending button once, and I know that both the ascending and descending buttons each work because they work perfectly when calling the fetch() request every time... I just thought that the global array will just capture the data from the initial fetch() request.它给出与 customSort(sortAscendingBy, "someAttribute") 相同的结果...就像数据按升序“卡住”只是因为我单击了一次升序按钮,而且我知道升序和降序按钮都有效,因为它们每次调用 fetch() 请求时都能完美运行...我只是认为全局数组只会从初始 fetch() 请求中捕获数据。

JSON looks like this: JSON 看起来像这样:

[   {
    "A": "A's value",
    "BList": [
      {
        "C": 1,
        "D": 2,
        "E": 3
      },
      {
        "C": 5,
        "D": 6,
        "E": 7
      }
    ]
      }
]

Sort functions look like this, these are the arguments passed as the sortOrder "callback function" parameter:排序函数如下所示,这些是作为 sortOrder“回调函数”参数传递的 arguments:

export function sortDescendingBy(prop) {
  return function (a, b) {
    
    if (a[prop] > b[prop]) return -1;
  };
}
export function sortAsendingBy(prop) {
  return function (a, b) {
    
    if (a[prop] > b[prop]) return 1;
  };
}

There is a problem with your sorting functions.您的排序功能有问题。 When you want to sort an array, you should return 1 or -1.当你想对一个数组进行排序时,你应该返回 1 或 -1。

Currently you only return one of them and the other value is undefined.目前你只返回其中一个,另一个值是未定义的。

Use this code:使用此代码:

export function sortDescendingBy(prop) {
  return function (a, b) {
    if (a[prop] > b[prop]) {
      return -1;
    } else {
      return 1;
    }
  };
}
export function sortAsendingBy(prop) {
  return function (a, b) {
    if (a[prop] > b[prop]) {
      return 1;
    } else {
      return -1;
    }
  };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 fetch() 和 vanilla JavaScript 伪造 .xhr 请求? - How do you fake a .xhr request using fetch() and vanilla JavaScript? 如何像在 jQuery 中一样过滤 vanilla Javascript 中的元素? - How to filter elements in vanilla Javascript like in jQuery? 在 JavaScript 中,如何以简单的方式检查“a”与“b”、“c”等? - In JavaScript, how do you check “a” against “b,” “c,” etc. in a simple manner? 如何在Javascript中按值排序或过滤JSON数据 - How to sort or filter JSON data by value in Javascript 您如何在JavaScript中实现类似静态方法的功能? - How do you implement something like a static method in JavaScript? JavaScript 是否在功能性 filter()、every() 等中缓存对 Object.keys() 的调用? - Is JavaScript caching calls to Object.keys() in functional filter(), every() etc.? 懒惰map,JavaScript中的filter,reduce等 - Lazily map, filter, reduce, etc. in JavaScript Vanilla JavaScript:如何动态创建一个在用户选择了一些文本后显示的按钮,然后对该文本执行一些操作? - Vanilla JavaScript: How to dynamically create a button that shows up after user has selected some text and then do something with that text? 是否可以在vanilla Javascript中同时运行多个if语句? 如果是这样你怎么样? - Is it possible to run multiple if statements at the same time in vanilla Javascript? If so how do you? 使用 lodash(或 vanilla javascript)对对象数组进行排序和过滤 - sort and filter an object array with lodash (or vanilla javascript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM