简体   繁体   中英

How to Create a Key - Value object from a list of objets

I am fairly new to react and have a query regarding how to create a key-value pair object in react using data returned to an axios get call to a webservice. Save the object in the state and later on read the values based on the keys.

axios.get('/api/locations/')
    .then(r => r.data )
    .then(types => this.setState({types}))

I am getting a List<LocationType> back from the backend and LocationType object has two property :

String locationId
String locationName

Now I want to create a hashmap using the types object as below:

{ "1": "London", "2": "Berlin"...... etc}

I am trying to do something like this but not really sure how i can assign the key value to a object

axios.get('/api/locations/types')
    .then(r => r.data )
    .then(types => this.setState({types}))
    .then(types => {
        this.state.types.map((type => {
            //create a map object and here but how?
        }))
    })

What is the best way to achieve this?

you can use reduce

this.setState(() => {
  return {
    types: types.reduce((map, type) => {
     map[type. locationId] = type.locationName;
     return map;
   }, {})
  }
})

To create a map of localionNames , run a loop on data and prepare an object first. Also instead of doing setState twice, you can do in one call.

Write it like this:

axios.get('/api/locations/types')
  .then(r => r.data)
  .then(types => {

    // map object
    let mapObj = {};

    // run a loop on types and create the map
    types.forEach((type, i) => {
      mapObj[type.locationId] = type.locationName;
    })

    // update all the values in single setState
    this.seState({ types, typesMap: mapObj })
  })

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