FoxOnFireHD
FoxOnFireHD

Reputation: 145

array.filter gives a undefined value

I have a json file with this structure:

{"year" : 1990, "fact": "Er waren oorspronkelijk maar drie seizoenen van de serie voorzien"}

On my website, I have episodes from a movie. They all have a release date. If the release date matches with the specific year in the JSON file, I want to show a fact that belongs to that year. I try to do that with this code:

const showFact = async () => {
        const year = document.querySelector(`.date`).textContent.split(` `)[2];
        const response = await fetch(`./assets/data/nice-to-know.json`);
        const facts = response.json();
        const fact = facts.filter(fact => fact.year == year).fact;
        document.querySelector(`.fact`).textContent = fact;
      }

If I console.log(fact) , I see that the fact is undefined

Upvotes: 0

Views: 181

Answers (4)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

Array.prototype.filter still returns an array, what you are looking for is Array.protoype.find instead

const facts = [
  {"year" : 1990, "fact": "1990 fact"},
  {"year" : 1991, "fact": "1991 fact"},
  {"year" : 1992, "fact": "1992 fact"},
  {"year" : 1993, "fact": "1993 fact"}
]
const fact = facts.find(fact => fact.year === 1990).fact;
console.log(fact);

Upvotes: 1

Lucas Noetzold
Lucas Noetzold

Reputation: 1740

As Federico pointed in the comments, you're trying to access a property on an array. When you filter facts it becomes an array, you need to map it.

const showFact = async () => {
        const year = document.querySelector(`.date`).textContent.split(` `)[2];
        const response = await fetch(`./assets/data/nice-to-know.json`);
        const facts = response.json();
        const factList = facts.filter(fact => fact.year == year).map(fact => fact.fact);
        document.querySelector(`.fact`).textContent = factList.join("<br>");
      }

above I used mapfunction to extract the facts to an array of only facts (without year), and then joined with a line break.

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

As I said in the comments, your problem is with

const fact = facts.filter(fact => fact.year == year).fact;

Because filter returns an array, which, of course, doesn't have a fact property.

Assuming filter returns a non-empty, single-element array, you probably meant.

const fact = facts.filter(fact => fact.year == year)[0].fact;

Upvotes: 1

FoxOnFireHD
FoxOnFireHD

Reputation: 145

const showFact = async () => {
    const year = document.querySelector(`.date`).textContent.split(` `)[2];
    const response = await fetch(`./assets/data/nice-to-know.json`);
    const facts = await response.json();
    const fact = facts.filter(fact => fact.year == year)[0].fact;
    document.querySelector(`.fact`).textContent = fact;
  }

array.filter returns an array. I just had to select the first item of that array.

Upvotes: 0

Related Questions