skip to Main Content

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?

3

Answers


  1. In order to get the properties of an object you can use for in loop, or Object.keys(yourObj)

    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]))
    Login or Signup to reply.
  2. A combination of Array::reduce() and Object.keys():

    const comments = [
     {K6TTWcffVUQNryy19FrSVKYL6Wt2: {age:25,name:"john"}}, 
     {AXYVWcffVUQNryy19FrSVKYL6Wt3: {age:35,name:"sue"}}
    ];
    
    const result = Object.keys(comments.reduce((r, el) => Object.assign(r, el), {}));
    
    console.log(result);
    Login or Signup to reply.
  3. You could map the keys.

    const
        comments = [{ K6TTWcffVUQNryy19FrSVKYL6Wt2: { age: 25, name: "john" } }, { AXYVWcffVUQNryy19FrSVKYL6Wt3: { age: 35, name: "sue" } }],
        keys = comments.flatMap(Object.keys);
    
    console.log(keys);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search