CHays412
CHays412

Reputation: 145

React map array and return only labels

I have a component in React which needs to map through a simple array:

var data = [{ older: 2 }, { "Nov 23": 0 }, { "Nov 24": 0 }, { "Nov 25": 3 }];

I need to map this array so it creates a new array of only the labels i.e.

["older", "Nov 23", "Nov 24", "Nov 25"]

How is this done? Thank you in advance.

Upvotes: 0

Views: 1700

Answers (3)

itidsu
itidsu

Reputation: 54

  var data = [{ "older": 2 }, { "Nov 23": 0 }, { "Nov 24": 0 }, { "Nov 25": 3 }];

  var keys = [];
  var labels = data.map(
    (value) => {
      keys.push(Object.keys(value)[0]);
    }  
  );

  console.log(keys);

Upvotes: 0

Luca Crea
Luca Crea

Reputation: 26

You have an array of objects and you want to get an array of strings.
You can use the map array method and the keys object method, like this:

var labels = data.map(obj => Object.keys(obj)[0])

you'll get:

// ["older", "Nov 23", "Nov 24", "Nov 25"]

Upvotes: 1

Anthony
Anthony

Reputation: 6482

You can use Object.keys() i.e.

var labels = data.map(x => Object.keys(x));

Upvotes: 0

Related Questions