0

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);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Tech Learner
  • 1,227
  • 6
  • 24
  • 59
  • 1
    Does this answer your question? [Get array of object's keys](https://stackoverflow.com/questions/8763125/get-array-of-objects-keys) – jonrsharpe Jul 19 '22 at 08:07
  • _"I am getting the result along with index 0"_ - because you're putting it in another array? What did you _think_ `propNames.push(Object.keys(el))` was doing? If you wanted them to be separate items, maybe `propNames.push(...Object.keys(el))`, but then given that you're looping over _one single thing_ that's just... `propNames = Object.keys(el)`. – jonrsharpe Jul 19 '22 at 08:09

3 Answers3

4

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]);
FZs
  • 16,581
  • 13
  • 41
  • 50
0

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);
Sana
  • 153
  • 1
  • 2
  • 13
0

Try this.

let propNames: Array<any> = [];
for (const key of Object.keys(tempVar[0])) {
  propNames.push(key)
}
console.log(propNames);
N.F.
  • 3,844
  • 3
  • 22
  • 53