Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find named indexes in array of objects?

Sorry if I mistyped the question, but I am not sure how to explain this question. I am showing the value that I want by code below. I have an array with named indexes:

const comments = [
 {K6TTWcffVUQNryy19FrSVKYL6Wt2: {age:25,name:"john"}}, 
 {AXYVWcffVUQNryy19FrSVKYL6Wt3: {age:35,name:"sue"}}
]

I am trying to find the named indxes of the array of objects. I mean I am trying to create an array of ["K6TTWcffVUQNryy19FrSVKYL6Wt2", "AXYVWcffVUQNryy19FrSVKYL6Wt3"] using the above comments array.

How can I achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

in order to get the (unknown) properties of an object you can use for in

const comments = [{
    K6TTWcffVUQNryy19FrSVKYL6Wt2: {
      age: 25,
      name: "john"
    }
  },
  {
    AXYVWcffVUQNryy19FrSVKYL6Wt3: {
      age: 35,
      name: "sue"
    }
  }
]

var result = comments.map(function(item) {
  for (var prop in item) {
    // the first one
    return prop
  }
})

console.log(result)

// or
console.log(comments.map(item => Object.keys(item)[0]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading