Pooja
Pooja

Reputation: 7

Read map data when you do not know the key and value in reactjs

I have data as :

 data =     [
            { 
                "name": "James Angus", 
                "age" : "22", 
                "job": "Dentist" 
            },
            { 
                "name": "Milan Howen", 
                "age" : "36", 
                "job": "Truck Driver" 
            }   
        ];

I am reading this as present :-

const renderItems = this.state.data.map(function(item, i) {
       return <li key = {i} > {item.name} < /li> 
 }

Here i am giving the key to read i.e. item.name So it reads all the name

But if i am not aware about key ... how should i iterate.

Means for all keys it should read the value without we specifying the key in reactjs.

I hope i am able to make my question clear .

Upvotes: 0

Views: 197

Answers (1)

Dev
Dev

Reputation: 3932

You can use Object.keys() API:

let data = [{
  "name": "James Angus",
  "age": "22",
  "job": "Dentist"
}, {
  "name": "Milan Howen",
  "age": "36",
  "job": "Truck Driver"
}];

data.map((item, id) => {
  Object.keys(item).map((key) => {
    console.log(item[key])
  })
})

You could also use Object.values() API

let data = [{
  "name": "James Angus",
  "age": "22",
  "job": "Dentist"
}, {
  "name": "Milan Howen",
  "age": "36",
  "job": "Truck Driver"
}];


data.map((item, id) => {
  console.log(Object.values(item))
})

Upvotes: 1

Related Questions