简体   繁体   中英

How to convert ES6 JSON object to dictionary?

I am really new to learning ES6 and JQuery so apologies if I am asking an already duplicated question (didnt find similar questions)

I am currently trying to get the data from the JSON file to work as the following

{
     EUR: { code: "EUR", symbol: "€", rate: "5,278.0518", … }
     GBP: { code: "GBP", symbol: "£", rate: "4,640.1577", … }
     USD: { code: "USD", symbol: "$", rate: "6,152.3500", … }
}

Here's the code I have so far:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {}
    this.performSearch()
  }

  performSearch(){
    const urlString = "https://api.coindesk.com/v1/bpi/currentprice.json";
    $.ajax({
      dataType: 'json',
      url: urlString,
      success: data => {
        console.log("This is in my data", data["bpi"])
    }
  })
  }

  render() {
    return (
      <div className="App">
        <p>This is a testing p</p>
      </div>
    );
  }
}

I want to iterate over my data["bpi"] so that I can iterate over all the keys and values in the dictionary.

However, because the dataType of data["bpi"] is undefined, I cannot use the forEach() method on here.

So how should I approach this without having to hard-code everything? (ie it works when I do console.log(data["bpi"]["EUR"]))

Thanks for your help

You can convert json object to array using Object.keys and iterate on that.

Example

Object.keys(data["bpi"]).map(key => data["bpi"][key]).forEach(item => console.log(item))

A couple things here.

data["bpi"] or data.bpi should not be undefined. It should be an object with 3 keys in this case.

Check how that data is coming back. If it's coming back as JSON you can call JSON.parse(data) to parse the data from a JSON object into a JavaScript object that you can then loop through.

Next, to iterate through the keys in the object -- data.bpi -- you can't use .forEach because that is an Array method. However, you can use a for.. in loop.

As others have stated, you can also use Object.keys to convert the object into an array of its and then run forEach onthat.

Example

const parsedData = JSON.parse(data)
for(var key in parsedData.bpi) {
    // do something here...
}

Object.keys(parsedData.bpi).forEach(key => parsedData.bpi[key] /* do something */ )

For iterating over objects you can do it as follows :

for(var keys in obj){
      var value = obj[key]
       .....
    }
  • in ES6 a new method called object.keys method was added which returns all the keys in an object

So

var keys = Object.keys(obj)
for(var i =0; i<keys.length; i++){
     var value = obj[keys[i]]
      ....
}

Your obj here will be data.bpi or data["bpi"]

I see that many people here use the following method to iterate over your Object :

for (let i in data.bpi) {
    // Your code
}

But should not use this method because it will also iterate on all enumerable properties of your object.

So here are better methods to use:

let keys = Object.keys(data.bpi)
for (let i = 0; i < keys.length; i++) {
    let item = data.bpi[i]
}

Or

let keys = Object.keys(data.bpi)
keys.forEach(e => {
    let item = data.bpi[e]
})

Or you can use for...of :

for (let i of data.bpi) {
    let item = i
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM