简体   繁体   中英

How to improve efficiency of this json search

I have some json data:

var data = {
  "version": "2.0",
  "result": {
      "0": [418789, 418790, 418791],
      "1": [431961, 431962, 431963], 
  }
};

And I have the value x I am looking for which in this case x = 431962 So to do this I have written a search function provided below:

for (var i = 0; i < Object.keys(data.result).length; i++) {
  for (var p = 0; p < Object.values(data.result)[i].length; p++) {
    if (Object.values(data.result)[i][p] == 418789) {
      console.log(Object.keys(data.result)[i])
    }
  }
}

However my issue is that this search function consists of 2 for loops which are nested so the speed is incredibly slow when searching through a large amount of JSON data, however I cannot seem to come up with a solution on how to improve efficiency and speed here.

This search is trying to find which key the value x exists in, where the key names in reality random names in no specific order, and the JSON data has a couple thousand keys with each array containing around 50 values from 1 to 1,000,000

One improvement you can make is to store references to the specific object/array you are working with so you don't have to return back to the Object.keys(...) again and again.

 let data = { "version": "2.0", "result": { "0": [418789, 418790, 418791], "1": [431961, 431962, 431963], } }; function findWhichArrayContainsValue(val) { for (key in data.result) { const candidateArray = data.result[key]; if (candidateArray.includes(val)) { return candidateArray; } } return undefined; } console.log(findWhichArrayContainsValue(418789)); console.log(findWhichArrayContainsValue(898989));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM