transform an array to an array consisting of objects

Below is an array list that needs to be converted into a specific form.

var data = [ "USA", "Denmark", "London"];

The desired format for the array is:

var data = [
 { "id" : 1, "label": "USA" },
 { "id" : 2, "label": "Denmark" },
 { "id" : 3, "label": "London" }
];

If you have a solution on how to achieve this conversion, please share with me.

Answer №2

Basic interpretation:

let convertedList = []
for (const index in dataList){
  convertedList.push({index: parseInt(index)+1, text: dataList[index]});
}

dataList = convertedList; //if you wish to replace the existing dataList

Answer №3

To iterate through the data array, you can utilize the forEach method.

var data = ["USA", "Denmark", "London"];
var newDataArray = [];
data.forEach(function(item, index) {
    newDataArray.push({
        id: index + 1,
        city: item
    });
});
console.log(newDataArray);

JSFIDDLE

Answer №4

Underscore provides a solution (suitable for older browsers that do not support Array.map):

var result = _.map(data, function(element, index){
    return {id: index + 1, label: element};
});

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

What is the quickest way to find and add together the two smallest numbers from a given array of numbers using JavaScript?

const getSumOfTwoSmallestNumbers = (numbers) => { const sortedNumbers = numbers.sort((a, b) => a - b); return sortedNumbers[0] + sortedNumbers[1]; } I encountered this challenge on Code Wars. My function to find the sum of the two smallest num ...

Jquery syntax for working with objects in Javascript

I am currently working on implementing a jQuery right mouse menu on my page, but I'm facing challenges in structuring it correctly for easy population. On my page, there is a list of items (an HTML table) that users can review. Depending on the user& ...

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

What is the process for running .js files on my browser from my local machine?

Hi there! I'm trying to figure out how I can create a JavaScript game in TextMate on my Mac. I want to have a regular .js file, then open it and run it in Chrome so that whatever I have coded - for example, "Hello World!" - will display in the browser ...

Update a div container using jQuery

Hey there, I need some help with a specific part of my code snippet: <div class="tags-column" id="tags"> <h2>Tags</h2> <ul> <% @presenter.tag_counters.each do |tag_counter| %> <li class=" ...

A guide on activating dropdown buttons individually using AngularJS (Cascading dropdowns)

When it comes to cascading dropdowns (for example: with 3 dropdowns), the challenge is to disable the 2nd and 3rd dropdown initially. Only when a user selects an option in the 1st dropdown, should the 2nd dropdown be enabled. Similarly, once an option is s ...

Double clicking on a row value in a Bootstrap table

Struggling to retrieve the row value after a double click in a bootstrap table. Unfortunately, every attempt returns 'undefined'. Snippet of my code: $('#table').on('dbl-click-row.bs.table', function(field, value, row, $el) ...

Refresh the current page in Next.js when a tab is clicked

I am currently working on a Next.js page located at /product While on the /product page, I want to be able to refresh the same page when I click on the product link in the top banner (navbar) that takes me back to /product. Is there a way to achieve this ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string var str = "2 Days, 2 Hours 10 Minutes"; When I use : str.split(/Days/); The result is: ["2 ", ", 2 Hours 10 Minutes"] This method seems useful to extract values like "days", "hours" and " ...

The array value has been shortened to a single digit

Utilizing PHP to generate dynamic checkboxes has presented an issue for me. While inspecting the elements in Chrome, I noticed that the values were echoing correctly. However, after processing $_POST data, all my values are somehow being truncated to just ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Experiencing Error: "Oops! encountering [$injector:unpr] error in angularjs despite correctly including my dependencies."

Here is a glimpse of my factory settings: app.factory('AuthenticationService',['$http', function ($http, $localStorage) { var AuthenticationService = {}; var api = 'http://del1-vm-kohls:8080/Survey' ; Authe ...

What is the best way to trigger a new api call after the previous one has successfully completed?

I'm just starting to learn about Angular and RxJS, and I have a specific scenario that I'm struggling with. I need to make a new API call after a previous one is successfully resolved within the Angular/RxJS context, but I'm not sure how to ...

Angular2 Animation for basic hover effect, no need for any state change

Can anyone assist me with ng2 animate? I am looking to create a simple hover effect based on the code snippet below: @Component({ selector: 'category', template : require('./category.component.html'), styleUrls: ['./ca ...

Using BeautifulSoup to Retrieve JPEG from an Image Tag's Src Attribute

Struggling with scraping this webpage for personal use. I am having trouble extracting the thumbnails of each item on the page. Despite being able to see image tags containing the required .jpgs when using "inspect" to view the html DOM, I cannot find the ...

Three.js experiencing issues with its Raycaster functionality

Currently, I'm working on a game where players navigate in a first-person view over dynamically generated uneven terrain using Perlin noise. To make the experience more realistic, I aim to incorporate gravity into the gameplay. For this purpose, I&apo ...

Is it possible for Spring Boot to initiate an action that will dynamically update an image in an HTML document using JavaScript or another method?

I am currently facing a challenge in updating an image on a website built with HTML, while utilizing Spring Boot as the backend technology. As of now, I am using JavaScript to update the image at regular intervals, but the timing does not align with when t ...

Harnessing the power of express middleware to seamlessly transfer res.local data to various routes

I am in the process of implementing a security check middleware that will be executed on the specific routes where I include it. Custom Middleware Implementation function SecurityCheckHelper(req, res, next){ apiKey = req.query.apiKey; security.securi ...