How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be

["Name", "Account", "Status"]
.

I attempted the code below, but the output was not what I expected. It includes the index 0 along with the result. Can someone provide guidance on how to achieve the desired outcome?

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

Answer №1

You're making it too complex.

If you want to access the initial element, simply use square brackets with tempVar: tempVar[0].

Next, retrieve the keys by invoking Object.keys() on it:

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

Answer №2

Check out this snippet of code:

const someValues: Array<any> = [];
dataVar= dataVar.splice(0,1);
for (let property in dataVar) 
{
  someValues.push(property)
}
console.log(someValues);

Answer №3

Give this a shot.

const properties: Array<any> = [];
for (const propertyName of Object.keys(sampleObject[0])) {
  properties.push(propertyName)
}
console.log(properties);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

"Triggering an AJAX POST request with a click event, unexpectedly receiving a GET response for

Hello there! I am currently attempting to send an AJAX POST request when a button is clicked. Below is the form and button that I am referring to: <form class="form-horizontal" > <fieldset> <!-- Form Name --> <legend> ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

SyntaxError: An invalid character was encountered (at file env.js, line 1, column 1)

This marks my debut question so kindly indulge me for a moment. I recently stumbled upon a guide that outlines how to dynamically alter environment variables in a React project without the need for re-building. You can find the guide here. The method work ...

Revise for embedded frame contents

Is it possible to modify the HTML content of an iframe within a webpage? I currently have this code snippet: <iframe src="sample.html"></iframe> I am looking for a way to edit the contents of sample.html without directly altering the HTML co ...

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

Avoid making API calls in every ngOnInit() function

I am currently developing an Angular front-end for a web-based application. One of the challenges I am facing is that all sub-page drill downs, implemented as different Angular components, make identical API calls in the ngOnInit() method. This repetitiv ...

The split() function returns a string that remains unaltered and intact, without any

I am attempting to separate this string: 120,00 m² into two distinct parts like this: 120 m² This is the code I have been using: var test = jQuery('#wpsight-listing-details-3 .span4:nth-child(4) .listing-details-value').html(); var pa ...

trigger a label click when a button is clicked

I am in need of assistance with simulating a label click when a button is clicked. I attempted to make the label the same size as the button so that when the button is clicked, it would check my checkbox. I then tried using JavaScript to simulate the label ...

Finding the current URL in React Router can be achieved by using specific methods and properties provided by

Currently, I'm diving into the world of react-redux with react-router. On one of my pages, it's crucial to know which page the user clicked on to be directed to this new page. Is there a method within react-router that allows me to access inform ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...

Reactjs is retrieving several items with just one click on individual items

I am having trouble getting only a single sub-category to display. Currently, when I click on a single category, all related sub-categories are showing up. For example, in the screenshot provided, under the Electronic category, there are two subcategories: ...

The type '{ id: string; }' cannot be assigned to the type 'DeepPartial<T>'

In my code, I am attempting to create a generic function that abstracts my repository infrastructure for creating a where clause. export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export int ...

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

Display a div based on search results

I recently encountered an issue with a script that needs modification to display different divs based on search criteria. Originally, I used this script for a contact list but now need it to perform another function. View the original code (JSFiddle) Here ...

What is the best way to send information back to an AJAX script that has made a

Can someone explain to me how the response section of an AJAX call is processed and formatted using plain, native JavaScript (no jQuery or other frameworks)? I have searched extensively but have not found a clear answer. I am looking for an example that ...

Creating a glowing shimmer using vanilla JavaScript

After successfully creating the Shimmer Loading Effect in my code, I encountered a hurdle when trying to implement it. The effect is visible during the initial render, but I struggle with utilizing it effectively. The text content from my HTML file does no ...