-1

I'm going through my code and neatening it up to make it easier to understand. In my code, I parse the same JSON at different points to get different data from the JSON.
I want to create a function which I call, and pass a parameter and it will return the information from the JSON.

My JSON looks like this:

{
    "Date": "11:10:02 28-02-19",
    "Number1": 2031,
}

The function I am trying to use is this:

function dataJson(key) {
  fetch("http://file/location/data.json?newversion") // supported in modern browsers.
      .then(res => res.json()) // parses into JSON. Fails if given improper json
      .then(data => {
        return data.key;
      })
}

and I am calling it within my script like:

dataJson(Date);

It should return 11:10:02 28-02-19 but I get the error

Uncaught ReferenceError: Date is not defined

And in VS Code it tells me that key is declared but never read. When I have this in my script I would just use data.Date and it would return what I want.

How do I call the function with a parameter and pass the parameter into the JSON parse to return the data I want?

JackU
  • 1,406
  • 3
  • 15
  • 43

1 Answers1

2

Uncaught ReferenceError: Date is not defined

Date is a variable name. You need a string. "Date".

And in VS Code it tells me that key is declared but never read.

.key doesn't refer to a variable. See also: Dynamically access object property using variable


NB: dataJson has no return statement so it isn't going to return anything. See also How do I return the response from an asynchronous call?.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • `dataJson` does have a return statement. `return data.key`. – JackU Feb 28 '19 at 11:19
  • @JackU — Wrong. That return statement belongs to the arrow function you pass to `then`. It doesn't belong to the `dataJson` function. – Quentin Feb 28 '19 at 11:19
  • That may be the case (which I didn't realise). However, the question was how do I pass the parameter `key` into `data.key`. – JackU Feb 28 '19 at 11:23
  • @JackU — See the first two paragraphs of this answer. – Quentin Feb 28 '19 at 11:23
  • I have taken on board your commets (I didn't understand to begin with). I am not using `data[key]`. How do I return this? If have `return` in the arrow function I get `undefined`, but if I define it as a variable and try to return outside the arrow function, I get nothing? How should I return it? – JackU Feb 28 '19 at 11:31
  • 1
    "I am not using data[key]" — Yes, that's the problem, you should be. – Quentin Feb 28 '19 at 11:33
  • "but if I define it as a variable and try to return outside the arrow function, I get nothing? How should I return it? " — See [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Quentin Feb 28 '19 at 11:34