add elements from one array to another array

I am facing a challenge in figuring out how to extract and push my array keys into a separate array, which I plan to use as column headings.

The code below successfully logs the keys from my data, but encounters an issue when trying to push them into another array:

    let cols = []

    data.forEach(function (obj, index) {
      if (index === 0)
      {
        console.log(Object.keys(obj));
        this.cols.push(Object.keys(obj));
    }
    });

I only need to extract the keys from the first object in the data array at the moment. Taking it one step at a time!

The expected end result for 'cols' would be ["ValueDate", "AccountName", "Holding"]

If you have any insights or suggestions, please share!

Thanks a lot! GWS

Data Sample:

[
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHAUD",
    "Holding": 318622.53
  },
  ...
  ...
  (remaining data elements truncated for brevity)
]

Answer №1

If you only want to check the first index, you can simply use Object.keys(data[0]). See the example below for reference.

data = [
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHAUD",
    "Holding": 318622.53
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHCAD",
    "Holding": 7195
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHEUR",
    "Holding": 5077.97
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHGBP",
    "Holding": 19625
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHJPY",
    "Holding": 16463
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHNZD",
    "Holding": 601.56
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHSGD",
    "Holding": 1000
  },
  {
    "ValueDate": "2017-04-26T14:16:00",
    "AccountName": "CASHUSD",
    "Holding": 1716906.25
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHAUD",
    "Holding": 318622.53
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHCAD",
    "Holding": 7195
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHEUR",
    "Holding": 5077.97
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHGBP",
    "Holding": 19625
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHJPY",
    "Holding": 16463
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHNZD",
    "Holding": 601.56
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHSGD",
    "Holding": 1000
  },
  {
    "ValueDate": "2017-04-27T14:16:00",
    "AccountName": "CASHUSD",
    "Holding": 1720781.25
  }
]

let cols = Object.keys(data[0])
console.log(cols)

Answer №2

utilize

for(let property in data){
}

array.forEach((element, index) => {
  if(index == 0){
    for(let prop in element){
       console.log(prop);
    }
  }  
});

for iterating through the object and accessing the keys

Answer №3

initialize empty array for cols

data.forEach((item, index) => {
  if (index === 0)
  {
    console.log(Object.keys(item));
    cols.push(Object.keys(item));
 }
});

display the contents of cols array

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

The issue arises when using NestJs with Fastify, as the code does not continue executing after the app.listen()

Greetings everyone, this is my inaugural question on this platform, so please forgive any oversights on my part. I have a query regarding my NestJs application configured to run with Fastify. Unlike Express, the code after the app.listen('port') ...

Endure the class attribute in Angular 5

My SearchComponent has a route (/search) and SearchDetailComponent has a route (/search-detail:id). In the SearchComponent, there is a searchbox (input field) where I can type any text to start a search. After loading the search results and navigating to ...

Display video exclusively on desktop using Next.js: useEffect is unable to update a React state on a component that is unmounted

I am facing an issue with my Next.js website where I want to render a video only on desktop and not on mobile. To achieve this, I created a custom React hook to track the window size using the isDesktop state variable. While everything seems to be working ...

Adding content to an Element Id using JavaScript can be done by utilizing the .insertAfter or .append methods. Since it involves a script tag, you cannot use the dollar sign

I need to include a script after a specific div in my HTML code. Here is what I currently have: <div id="uno">insert after this</div><br /> <p>this is a paragraph</p><br /> <div>this is a div</div> var mysc ...

Seeking a POST request to a specific URL

Hey there! I'm currently working on developing an Airtime application and need some guidance. Here's what I need help with: To send airtime, I have to make a HTTP POST request to one of the following endpoints: Live: Sandbox: These are the req ...

Setting a two-dimensional double array by using a one-dimensional array of strings, with each string pointing to another one-dimensional array of doubles

I need to handle 4 arrays of size 3 in my code where I generate values to store in those arrays and then save them in an output file. I'm looking for a more elegant and best practice implementation than using a double array and a for loop. One idea I ...

JavaScript can be used to append multiple array values within double brackets in Spring MVC

I am currently developing an application using Spring MVC with MongoDB. In the collection, I have retrieved multiple image name values: Ex: 1.jpg, 2.jpg, 3.jpg.... My Query: Now I need to place these values inside double brackets [[]] Ex : [["1.jpg"," ...

Ways to transfer information between controllers in my situation

I am attempting to send data to my controller using the State Provider. This is an example of what I have: app.js $stateProvider .state('test', { url: '/te', views: { '&ap ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

Attempting to modify information in vue.js

I have been facing an issue with overriding data in the App.vue component. It seems that every time I try to update the data in my main.js file, the component still takes the default data. I am working with webpack as well. App.vue <template> & ...

Mapping TypeScript function return types based on parameter conditions using dictionaries

I'm trying to create a function in Typescript that will return different objects depending on the function parameter. Can someone help me find a solution? This is what I have so far: type outputMap = { 'x': number, 'y': st ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

What is the best way to refresh only the table and not the entire page in a React Js application?

I have created a code that displays loading.. message before the entire content appears. However, I only want to load the table itself. I attempted to separate the "List of Employee" from the button, but unfortunately, it did not work as expect ...

Tips for updating the secure route with TypeScript and React-Router versions 4, 5, or 6

I've been attempting to create a <PrivateRoute> based on the example in the react-router documentation using TypeScript. Can someone provide assistance? The PrivateRoute from the react-router documentation: const PrivateRoute = ({ component: Co ...

"Having trouble with my Ajax Post - seeking an easy solution

I am having trouble with a simple Ajax post request. Here is my code snippet: <html> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> var deviceDetails = []; ...

When using react, it is not possible to have a <span> element as a child of a <

I designed a custom select dropdown feature for use in a redux-form within a react-redux application. The dropdown functions well, with no performance issues, but I am encountering a warning in the browser. Warning: validateDOMNesting(...): <span> c ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

What are the steps to utilizing objects in Javascript asynchronously?

Prior to delving into the query process, it's important to note that the issues object is defined at the start but becomes undefined within the issues query. Despite attempting solutions found on similar posts, none proved successful. Detailed comment ...

Ways to retrieve anchor tag values from an AJAX response without a defined class

if(ajaxRequest.readyState == 4) { var response = ajaxRequest.responseText; response=response.split('^^--^^'); var buname=response[5].split('^^|||^^'); //rest code } The AJAX request has returned the following code, now stored in the va ...

What is the best way to modify the properties of an object as soon as a specific condition is satisfied

I'm currently working on enabling a button transition from .disabled = true to .disabled = false. My project involves creating a Yahtzee game clone for entertainment, where players need to select a score to keep after their third roll. Once that choic ...