Dumblydorr
Dumblydorr

Reputation: 152

Map react data to single array

So I am trying to create a simple array that lists all the items that have been mapped. All other options around here seem much to complex for what I'm trying to do.

The code that gets my data is:

componentDidMount() {
    fetch('http://localhost:9000/api/get/locations')
      .then(res => res.json())
      .then(res => {
        if (res && res.data) {
          this.setState({ apiResponse: [...this.state.apiResponse, ...res.data] })
        }
      });
  }

I can them map it into something like a list using this code:

getLocations() {
    if (this.state.apiResponse.length <= 0) {
      return <div>Loading...</div>
    } else {
      return this.state.apiResponse.map((val, key) => {
        return <li key={key}> {val.name} </li>
      })
    }
  }

However, I want to have an array that such as "locations" So that each value is mapped to an item in an array.

Example (of code that would not work):

const locations = []

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      return <div>Loading...</div>
    } else {
      return this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...{id: key, value: val.name, isChecked=false}]
      })
    }
  }


# Output:

locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]

Is there a way to do this simply? or another way to go around doing it?

Upvotes: 0

Views: 62

Answers (2)

rajan magar
rajan magar

Reputation: 11

Try this instead:

this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...[{id: key, value: val.name, isChecked=false}]]
})

Upvotes: 0

Nadun
Nadun

Reputation: 7853

You can take the desired output using a map like this, in fact this the basic usage of map,

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      locations = [];
    } else {
      locations = this.state.apiResponse.map((val, key) => {id: key, value: val.name, isChecked=false});
    }
  }

this will give an output like this:

locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]

please let me know if you need more information.

Upvotes: 1

Related Questions