0

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.

0

3 Answers 3

1

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"]

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0
  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);

1 Comment

Hi @onurkaya, you're relatively new here so I'd like to recommend that you take a look at the guide how do I write a good answer. It's always good to have a explanation about your solution, not just code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.