Freddy Sidauruk
Freddy Sidauruk

Reputation: 292

Return key name of array of object

i have data from API and all works perfectly but how can i get key name only to fetch outside map ?

this is my data json

[
  {
      "topic": "HAIRPORT",
      "percentage": 90
  }, 
  {
      "topic": "TECHTRIX",
      "percentage": 67
  }
]

and this is my current code

const data = this.state.topics;
console.log(data)

All i want to get key name Percentage and Topic outside map or for

so here is i upload the imagesenter image description here

Upvotes: 1

Views: 75

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58593

Try to use :

Object.keys(this.state.topics[0])

const data = [
  {
      "topic": "HAIRPORT",
      "percentage": 90
  }, 
  {
      "topic": "TECHTRIX",
      "percentage": 67
  }
]

const keys = Object.keys(data[0]);

console.log(keys);
console.log(keys[0]);
console.log(keys[1]);

Upvotes: 1

Mamun
Mamun

Reputation: 68923

Loop through the array then use for..in to find the key in each object. Try the following way:

var data = [
  {
      "topic": "HAIRPORT",
      "percentage": 90
  }, 
  {
      "topic": "TECHTRIX",
      "percentage": 67
  }
];
data.forEach(function(item, i){
  for(var key in item)
    console.log(key)
});

Upvotes: 1

Related Questions