Home > Back-end >  How to retrieve first object's property names of an object array?
How to retrieve first object's property names of an object array?

Time:07-19

I have an object array with below structure and I need to get first object's property names alone from this array and not values. My result should only have ["Name" , "Account", "Status"].

I tried below lines of code but the result was not as expected. I am getting the result along with index 0. Can someone guide me here to achieve the result.

tempVar=   [
      {
        "Name"    : "A1",
        "Account" : "Dom",
        "Status"  : "A"
      },
      {
        "Name"    : "A5",
        "IntAccount" : "Int",
        "Status"  : "A"
      },
      {
        "Name"    : "A2",
        "LclAccount" : "Lcl",
        "Status"  : "A"
      },
      {
        "Name"    : "A4",
        "UnknownAccount" : "UA",
        "Status"  : "A"
      }
    ];
let propNames: Array<any> = [];
tempVar= tempVar.splice(0,1);
for (let el of tempVar) 
{
  propNames.push(Object.keys(el))
}
console.log(propNames);

CodePudding user response:

You're overcomplicating it.

To get the first element, index tempVar with square brackets: tempVar[0].

Then, to get the keys, just call Object.keys() on it:

const propNames = Object.keys(tempVar[0]);

CodePudding user response:

Try the following lines of code:

let propNames: Array<any> = [];
tempVar= tempVar.splice(0,1);
for (let key in tempVar) 
{
  propNames.push(key)
}
console.log(propNames);

CodePudding user response:

Try this.

let propNames: Array<any> = [];
for (const key of Object.keys(tempVar[0])) {
  propNames.push(key)
}
console.log(propNames);
  • Related