0

I have a json that looks like this:

const sitesList = 
{"sites": {
  "miami": {
    "name": "Miami Beach"
  },
  "london": {
    "name": "London Bridge"
  }
}}

I also have a function that takes an array as parameter. The values in this array might be "london", "miami" or both etc. This is the function:

async function readPDF2(sites) {
  for (const value of sites) {
    console.log(sitesList.sites.value.name);
  }
}

The function is called like this: readPDF2(['miami']);

Now the problem is that when I do sitesList.sites.value.name, Javascript interprets value as an actual part of the json object. This makes sense, but how do I get around this? I want it to treat value as the constant declared in the for loop.

See this image:

enter image description here

How would I obtain this? Thanks for any input!

Leomania
  • 79
  • 1
  • 4
  • 1
    Does this answer your question? [Using variable keys to access values in JavaScript objects](https://stackoverflow.com/questions/922544/using-variable-keys-to-access-values-in-javascript-objects) – aaandri98 Sep 06 '21 at 15:34
  • Enclose `value` in square braces to use it as an expression that evaluates to a key: `console.log(sitesList.sites[value].name);` – danh Sep 06 '21 at 15:39
  • Thanks @danh, this was the solution I was looking for :) – Leomania Sep 06 '21 at 17:23
  • ```Object.values(sitesList.sites).forEach((value)=>{console.log(value.name)})``` – ANOL GHOSH Sep 07 '21 at 16:16

2 Answers2

0

You can use Object.entries()

const sitesList = {
  "sites": {
    "miami": {
      "name": "Miami Beach"
    },
    "london": {
      "name": "London Bridge"
    }
  }
}


const sites = sitesList.sites;
for (const [key, value] of Object.entries(sites)) {
  console.log(`Key: ${key} value: ${value.name}`)
}

Or you can use for in

const sitesList = {
  "sites": {
    "miami": {
      "name": "Miami Beach"
    },
    "london": {
      "name": "London Bridge"
    }
  }
}


const sites = sitesList.sites;
for (const site in sites) {
  console.log(`Key: ${site} value: ${sites[site].name}`)
}
Thammarith
  • 662
  • 5
  • 19
0

const sitesList = {
  "sites": {
    "miami": {
      "name": "Miami Beach"
    },
    "london": {
      "name": "London Bridge"
    }
  }
}
//If you need only Value then try this,
Object.values(sitesList.sites).forEach((value)=>{console.log(value.name)})

//If you need only Key then try this,

Object.keys(sitesList.sites).forEach(key=>{console.log(key)})

//If you need both Key and Value then try this,

Object.entries(sitesList.sites).forEach(([key, value]) => console.log(`${key}: ${value.name}`))
ANOL GHOSH
  • 1
  • 1
  • 9