EN VI

Javascript - How to find named indexes in array of objects?

2024-03-15 04:00:08
Javascript - 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?

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

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login