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);
Advertisement
Answer
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]);