-1
{
"Centers": {
    "Athens": [
        {
            "name":"name1",
            "lat":"",
            "lon":"",
            "address":"address1",
            "tel":"",
            "email":"",
            "link":""
        },
        {
            "name":"name2",
            "lat":"",
            "lon":"",
            "address":"address2",
            "tel":"",
            "email":"",
            "link":""
        }       
    ]
}
}

I have this JSON file and I want to get the address of an element I specify using its name. Something like this:

alert( stores.Centers.Athens["name"=="name1"].address );

Is there any way I can achieve this, or should I remake my JSON file?

Edit:

.find(x => x.name === 'name1') doesn't work. It returns 'undefined'. findIndex() also returns '-1'. I suspect it's because it is a JSON file and not an object list, meaning the property keys are doublequoted.

Smirlianos
  • 5
  • 1
  • 6
  • "_`.find(x => x.name === 'name1')` doesn't work._" [Yes it does](https://jsfiddle.net/j1a0do4n/). If stores contains the properly parsed JSON, it should work fine. If it isn't properly parsed, then `stores.Centers` should already be `undefined`. You'll need to provide a [mcve] for us to be able to help you further. – Ivar Nov 03 '21 at 11:11

1 Answers1

-1

You can easiy achieve the result using find and optional chaining

stores.Centers.Athens.find((o) => o.name === "name1")?.address

const stores = {
  Centers: {
    Athens: [
      {
        name: "name1",
        lat: "",
        lon: "",
        address: "address1",
        tel: "",
        email: "",
        link: "",
      },
      {
        name: "name2",
        lat: "",
        lon: "",
        address: "address2",
        tel: "",
        email: "",
        link: "",
      },
    ],
  },
};
const address = stores.Centers.Athens.find((o) => o.name === "name1")?.address;
console.log(address);
DecPK
  • 24,537
  • 6
  • 26
  • 42