Home > front end >  fetching data from json file in js
fetching data from json file in js

Time:06-22

I'm trying to fetch data from an external json file called comuni.json, here it is a preview:

[
    {
      "codice": "A001",
      "comune": "ABANO TERME",
      "provincia": "PD"
    },
    {
      "codice": "A004",
      "comune": "ABBADIA CERRETO",
      "provincia": "LO"
    }
]

My goal is to get the "codice" value of the respective "provincia" element. What I mean is that if the user type PD the script gets A001. However if the user type LO the script gets A004. I hope I express myself well.

My script looks like this:

const jsonfile = require('./comuni.json');
var data = JSON.parse(jsonfile)
var i;
for (i in data){
  if (data[txt_placeBirthday]instanceof Object){
    let codice_castale = data[txt_placeBirthday]['codice']
    return codice_castale
  }
}

However I don't know how to proceed, I searched online but nothing really helped. Does anyone have any idea?

CodePudding user response:

Just by find() method.

const inputValue = "PD"

const dataBackFromApi = [
    {
      "codice": "A001",
      "comune": "ABANO TERME",
      "provincia": "PD"
    },
    {
      "codice": "A004",
      "comune": "ABBADIA CERRETO",
      "provincia": "LO"
    }
]

const codice = dataBackFromApi.find(ele => ele.provincia === inputValue)?.codice

console.log(codice)

CodePudding user response:

You can take advantage of Array.prototype.find. This allows you get the first match that matches your test, in this case matching provincia to a value. If no match was found it returns undefined so you can either test for undefined or use ?..

const data = [
    {
      "codice": "A001",
      "comune": "ABANO TERME",
      "provincia": "PD"
    },
    {
      "codice": "A004",
      "comune": "ABBADIA CERRETO",
      "provincia": "LO"
    }
];

const result = data.find(item => item.provincia === "PD");

if (result !== undefined) {
  console.log(result.codice);
} else {
  console.error('Could not find ...');
}

// or

console.log(result?.codice);

  • Related