Reputation: 145
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
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
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
Reputation: 6482
You can use Object.keys()
i.e.
var labels = data.map(x => Object.keys(x));
Upvotes: 0