Studentofcode
Studentofcode

Reputation: 45

How to fetch Json nested and Make it Array of object in React

I'm setting up an array of list, and want to parse the value from JSON to that list

This is the array

const universityOptions = [
  { key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
  { key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
  { key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
  { key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
  { key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
  { key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]

Below is the json

{"success":true,"data":[{"id":1,"name":"University 1"},{"id":2,"name":"University 2"},{"id":3,"name":"University 3"},{"id":4,"name":"University 4"},{"id":5,"name":"University 5"},{"id":6,"name":"University 6"}]}

and this is the method i tried so far, which i get the data but i only need the data.name (university name) and i'm stuck how to get it

componentDidMount() {
    const univFetch = fetch('url')
    // university_list state
    univFetch.then(res => {
      if( res.status === 200)
      return res.json() 
    }).then( univJson => {
      this.setState({
        university_list: univJson.data
      })
      console.log(univJson.data);
    })
}

Result

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: "University 1"}
1: {id: 2, name: "University 2"}
2: {id: 3, name: "University 3"}
3: {id: 4, name: "University 4"}
4: {id: 5, name: "University 5"}
5: {id: 6, name: "University 6"}
length: 6
__proto__: Array(0)

I expect the output is an array like

const universityOptions = [
  { key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
  { key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
  { key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
  { key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
  { key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
  { key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]

Thanks

Upvotes: 1

Views: 158

Answers (4)

ANUPAM CHAUDHARY
ANUPAM CHAUDHARY

Reputation: 151

Why not perform an extra operation,

componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
  if( res.status === 200)
  return res.json() 
}).then( univJson => {
   var output = [];
   for(var i=0 ;i<univJson.data;i++){
       var obj = {key : univJson.data[i]["id"],
                  text : univJson.data[i]["name"],
                  value : univJson.data[i]["name"]
   }
   output.push(obj)
   }
   this.setState({
        university_list: output
   });
  console.log(output);
})
}

Upvotes: 0

AxelJunes
AxelJunes

Reputation: 656

Try it like this:

const newArray = json.data.map(elem => ({
  key: elem.id.toString(),
  text: elem.name,
  value: elem.name
}));

Your componentDidMount() would end up being something like this:

componentDidMount() {
  const univFetch = fetch('url')

  univFetch.then(res => {
    if( res.status === 200)
    return res.json() 
  }).then( univJson => {
    const universityList = univJson.data.map(elem => ({
      key: elem.id.toString(),
      text: elem.name,
      value: elem.name
    }));

    this.setState({
      university_list: universityList
    })
  })
}

Here's the Sandbox if you want to take a look at it. Hope it helps.

Upvotes: 1

Engineer
Engineer

Reputation: 1261

Error is use forEach on univJson and create an array

  componentDidMount() {
        const univFetch = fetch('url')
        // university_list state
        univFetch.then(res => {
          if( res.status === 200)
          return res.json() 
        }).then( univJson => {
          let univArray = [];
          univJson.forEach((datum, index) => {
            univArray.push({ key: datum.id, text: datum.name, value: datum.name});
          })
          this.setState({
            university_list: univArray
          })
          console.log(univJson.data);
        })
      }

Upvotes: 0

ravibagul91
ravibagul91

Reputation: 20755

You need to iterate over your response and you can create desired output like this,

this.setState({
    university_list : univJson.data.map(data => ({key:data.id,text:data.name,value:data.name}))
}, ()=>console.log(this.state.university_list))

Upvotes: 0

Related Questions