0

I want to be able to fetch data from a JSON file only if a value of a key matches that of an already stored variable in my script. For example, I have two stored variables:

  • Weather, which has a value of hot.
  • Distance, which has a value of 4.

I want to return only the objects in the JSON file that have these key value pairs and save the objects into an array. Any help would be much appreciated.

Heres my json file called 'locations.json':

[
  {
    "Distance ": 2,
    "Weather": "cold"
  },
  {
    "Distance ": 4,
    "Weather": "hot"
  },
  {
    "Distance ": 3,
    "Weather": "cold"
  },
  {
    "Distance ": 4,
    "Weather": "hot"
  }
]
cyqsimon
  • 2,752
  • 2
  • 17
  • 38
tomhuckle
  • 25
  • 3
  • 1
    You can use `array#find` for this. – Hassan Imam Mar 09 '23 at 13:17
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+filter+object+array+more+than+one+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Mar 09 '23 at 13:19
  • @HassanImam that will only find ONE object. They need [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – mplungjan Mar 09 '23 at 13:21
  • Be careful, you have a space in the Distance key. The code could be this: `const dist = 4, wthr = "hot"; const arr = data.filter(({Distance,Weather}) => Distance === dist && Weather === wthr);` – mplungjan Mar 09 '23 at 13:24
  • Thanks. In order to get the data, do I use fetch()? – tomhuckle Mar 09 '23 at 14:03

0 Answers0