0

I have an array for instance

humans:[
  dave: {
   ...daveData
  },
  mike: { 
   ...mikeData
  }
]

now calling human[0] returns {..daveData} but how can I get the NAME of the KEY meaning 'dave', 'mike' as a string ... sorry if I'm repeating myself, but I didn't find similar questions.

Also to say im using React to render

tags using array.map()

6
  • 2
    That's invalid data. Commented Feb 6, 2018 at 11:30
  • 2
    Hi there, the code example you provided is not valid JavaScript format. Can you provide working code? Commented Feb 6, 2018 at 11:30
  • Possible duplicate of Javascript get object key name Commented Feb 6, 2018 at 11:32
  • I'm pulling the data from Firebase ... firebase creates for me an array of objects, each object has some "-L4eimbEHuoYMpmkGVTs" random Id ... and i need this ID as a string Commented Feb 6, 2018 at 11:32
  • Did you mean: {humans:[{dave: {...}}, {mike: { ... }}]} or [{dave: {...}}, {mike: { ... }}]?? Commented Feb 6, 2018 at 11:33

2 Answers 2

1

Your array is invalid, assuming from the comments your array is like this:

const humans = [
  {
   dave: 'bar' // or whatever, doesn't need to be a string
  },
  {
   mike: 'baz'
  }
];

then you could:

const humans = [
  {
   dave: 'bar'
  },
  {
   mike: 'baz'
  }
];

const myKeys = humans.map(x => Object.keys(x)[0]);

console.log(myKeys)

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

Comments

0

You can use reduce function and spread operator.

Look at this code snippet

var data = [{dave: {}}, {mike: {}}, {'Георги': {}}, {'Димитранов': {}}];

var results = data.reduce((a, c) => [...a, ...Object.keys(c)], []);

console.log(results);

Resources

Comments

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.