Transform JavaScript array into a different JavaScript array structure

Check out my JavaScript array below:

["name", "age", "gender"]

I am looking to transform it into this:

properties: [
        {
          key: "Name",
          value: "name",
        },
        {
          key: "Age",
          value: "age",
        },
        {
          key: "Gender",
          value: "gender",
        }
      ],

Can anyone guide me on how to structure the JavaScript array in the specified format above?

Answer №1

If you want to manipulate array elements, you can utilize functions like map(), charAt(), toUpperCase(), and slice(). Here is an example of how you can use them:

var arr = ["field", "description", "example"];
var columnDefs = arr.map((item, i) => ({headerName: item.charAt(0).toUpperCase() + item.slice(1), field: item}));
console.log(columnDefs);

Answer №2

Utilizing the powerful Array.map method, you have the ability to convert each item into the desired format for the output.

In addition, by employing the toUpperCase() function, you can easily ensure that each field is capitalized.

const arr = ["field", "description", "example"];
const output = {
  columnDefs: arr.map((item) => ({
    headerName: `${item[0].toUpperCase()}${item.substring(1)}`,
    field: item
  }))
};

console.log(output);

Answer №3

const tableColumns = []

data.forEach(item=>{
  let column = {
    'headerName': item.charAt(0).toUpperCase() + item.slice(1),
    'field': item
  }
  tableColumns.push(column)
}

Answer №4

array.forEach(element => ({ title: element.toUpperCase(), content: element }))

Give this a try, it should get the job done.

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

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

Sending data from a partial view to a controller

Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add butt ...

Organizing and handling a multitude of variables

In my current project, I find myself dealing with classes that consist of numerous variables, making it a challenge to keep track of them all. Specifically, there are certain types of variables associated with recurring "items" within the class that need t ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Creating an image from a webpage by utilizing JavaScript

Similar Question: Using HTML5/Canvas/Javascript to capture web page as an image I have a webpage where I fetch details from a database and display them in a table format. I would like to save this page as an image so that I can email it to the user. C ...

Switch the contenteditable HTML attribute in a dynamically generated table using PHP

Despite finding numerous articles and solutions, my code still refuses to work. What could I be overlooking? Below is a snippet of the code where the crucial part is marked at the comment '! HERE') <!-- Table with grades --> <table clas ...

What is the best way to eliminate elements from an array that do not match a certain

I am having trouble removing all elements that contain @b.com from an array. Even when I remove the !, the result is stil an empty array. This makes me think that I might be making a mistake somewhere. Could someone please help me understand where I' ...

A ReferenceError was thrown because angular is not defined within the angular-moment.js script

After spending an hour trying to figure out what went wrong, I still can't solve this problem. I've searched on stackoverflow for answers, but nothing seems to be helpful. The issue arises when trying to integrate Moment js into my project. Che ...

Enhance videojs player source with personalized headers

Currently, I have a backend API running on Express that manages a streaming video m3u8 file. The endpoint for this file is: http://localhost:3000/api/stream.m3u8 It is important to note that access to this endpoint requires a valid user token. router r ...

What is the best way to display a specific object prop on a page after triggering the onChange() method from a selected

Looking to simplify some code that's become a bit overwhelming. My pizza order consists of arrays for size and price. I'm trying to update the price when a user selects a size, but I've been stuck on an issue with mapping pizzas from the ca ...

React Native's SQLite storage library does not seem to be providing any response

Currently, I am utilizing the SQLite database through react-native-sqlite-storage. However, when attempting to display the result in an alert, it shows as undefined. I have also attempted performing the operation without using await and async. MainFil ...

ng-bind stops updating after entering text into input field

I am a newcomer to AngularJS and I have encountered an issue that I am struggling to resolve. Although I found a similar question on stackoverflow, the solution provided did not work for me. The problem I am facing is that when I input text into any of the ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Problem where ipcMain.handle() fails to send a value back to ipcRenderer.invoke()

After spending 2 days struggling with this problem, scouring the API documentation of Electron.js and various websites, I am turning to you all as my final hope: Here are the 3 files that are causing the issue: main.ts (excerpt): app.whenReady().then(() ...

Struggling with resizing pointer arrays and encountering issues

Just to clarify, I am working on an assignment where I have to resize two pointer arrays containing objects. The custArray consists of 3 elements while gArray has only 1. My task is to transfer a specific object from custArray to gArray, resulting in both ...

Analyzing JSON data in client-side JavaScript that has been transmitted from a Node.js server

Trying to check out some JSON in the chrome console that was sent from a NodeJS file. No errors are showing up, but for some reason, I can't see the message "hello world" The NodeJS file sends the JSON message after an HTML form is filled o ...

Explaining how to iterate through objects (one by one) in the This.questionnaire.Profile at every click using JavaScript (answer not found in forums)

Creating a series of questions, each part being stored in This.question = {p1: {...}, p2: {...}, p3: {...}, p4: {...}, p5: {...} etc. (and many more). I want to be able to switch from one article to the next every time I click a button... click => next ...

What is the method for displaying a canvas scene within a designated div element?

I need help displaying a scene inside an existing div on my webpage. Whenever I try to do this, the canvas is always added at the top of the page. I attempted to use getElementById but unfortunately, it didn't work as expected. What could I be overlo ...