Home > Back-end >  Copying data of one array with transformation into another array in javascript/react
Copying data of one array with transformation into another array in javascript/react

Time:01-21

My API is returning below output.

[
    "ANT",
    "ARG",
    "ARM",
    "BUR",
    "UAE"
]

in my array I need to store countryname corresponding to these countrycode. so for that I have used country-data library in react. so I can get output like console.log(countries["UAE"].name); I need to store country name in my countryData array which is declared below.

my react code is.

 this.state = {
      countryData: [],
    };

I am using arraycode like below.

updateDropdownData() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {        
      res.data.map((code) => {
        alert(countries[code].name);
        countryData.push.apply(countryData, countries[code].name);
      });
      this.setState({ countryData });
    });
  }

but I am getting error

index.bundle.js:122 Uncaught (in promise) ReferenceError: countryData is not defined
    at index.bundle.js:122:217123
    at Array.map (<anonymous>)

what mistake I am doing. I am quite new in javascript and react.

Edit1:- alert(countries[res.data[0]].name); //this line is working.

but const _countryData = res.data.map((code) => countries[code].name); giving error. enter image description here

CodePudding user response:

Changing the state value directly does not fit React's method.

updateDropdownData() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const _countryData = res.data.map((code) => countries[code].name )        
      this.setState({ countryData: _countryData });
    });
  }

EDIT

The countries variable must be where you run it. And the shape of the variable should be as follows.

const countries = {
    "ANT" : { name : "ant_name"  },
    "ARG" : { name : "arg_name"  },
    ...
}
  •  Tags:  
  • Related