Transforming a 2D array into an array of objects

Here is an example of an array:

let heroes = [
  ["1", "Tony Stark"],
  ["2", "Steve Rogers"],
  ["3", "Thor"],
  ["4", "Nick Fury"]
];

I am looking to transform this array into an object with the following structure:

let avengers = [
  {id:"1", name:"Tony Stark"},
  {id:"2", name:"Steve Rogers"},
  {id:"3", name:"Thor"},
  {id:"4", name:"Nick Fury"}
];

Answer №1

To simplify the array, consider destructuring it to create a new object using short-hand properties.

let heroes = [["1", "tony stark"], ["2", "steve rogers"], ["3", "thor"], ["4", "nick fury"]],
    updatedHeroes = heroes.map(([id, name]) => ({ id, name }));
 
console.log(updatedHeroes);

Answer №2

You can iterate through your array to create new objects

const heroes = [
  ["1", "Iron Man"],
  ["2", "Captain America"],
  ["3", "Thor"],
  ["4", "Black Widow"]
];

var heroObjects = heroes.map((hero) => {
  return {
    id: hero[0],
    name: hero[1]
  };
})

console.log(heroObjects)

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

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

What is the best way to compare characters within a single string in SAS that are separated by slashes (/)?

New to SAS and seeking help with a dataset called data: id string 1 Comm Bank/Comm Bank 2 Comm Bank/Cash Flow 3 Financial Statement/Financial Statement/Financial Statement 4 Comm Bank/Wealth Management/Real Estate 5 Comm ...

Tips for sending the setState function to a different function and utilizing it to identify values in a material-ui select and manage the "value is undefined" issue

I am currently utilizing a Material UI select component that is populated with data from an array containing values and options. Within this array, there exists a nested object property named "setFilter". The setFilter property holds the value of setState ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

Synk: the presence of a self-signed certificate within the certificate chain

Recently, I've been encountering the error message Synk Protect is showing "self-signed certificate in certificate chain" when I try to run npm install on a project of mine. Would appreciate any help or tips on how to identify which out of the 984 pac ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

Using React JS, how to easily upload a CSV file to Amazon S3 with your AWS credentials

Seeking guidance on how to utilize AWS credentials to upload a CSV file using React S3 Uploader. The code snippet I've tried so far is as follows: import React, { PureComponent } from "react"; import ReactS3Uploader from "react-s3-uploader"; sav ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Accessing array using mysqli

I am in the process of updating some old PHP code that utilized MySQL to now using MySQLi. The revised code I have is as follows: function mysql_fetch_full_result_array($result){ global $dbc; $table_result=array(); $r=0; while($row = mysqli_ ...

Is it possible to insert an image directly into the <img> tag without having to first send it to the server?

I've created an upload form that allows users to submit images: <form> <input accept="image/jpeg, image/gif, image/png" type="file" name="image" id="image" class="UploadInput" onchange="submitImageUploaderForm()"/> </form> Once t ...

vertical lines alongside the y-axis in a d3 bar graph

https://jsfiddle.net/betasquirrel/pnyn7vzj/1/ showcases the method for adding horizontal lines along the y axis in this plunkr. I attempted to implement the following CSS code: .axis path, .axis line { fill: none; stroke: #000; } I am lo ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...

The initial update of ng-model is not occurring

I am currently working on a checkbox functionality in my project that is bound to an ng-model: <input type="checkbox" ng-change="toggleAll(globalChecked)" ng-model="globalChecked"> The toggleAll function is responsible for accessing the globalCheck ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Updating an array of objects within an array using another array of objects

There are two JavaScript Arrays: let x = [ { id: 'Abc', children: [ { id: 12, name: 'john' }, { id: 13, name: 'dow' ...

Sort through nested objects

Trying to filter an array of movies by genre using a function but encountering a TypeError: TypeError: movie.genres.some is not a function. (in 'movie.genres.some(function(item){return item.name === genre;})', 'movie.genres.some' is und ...

Choosing an index on material io with setSelectedIndex

I am currently working on modifying select-menus to adjust the selected index: let filterField= mdc.select.MDCSelect.attachTo( document.querySelector(".mdc-select--location") ); This is how I am connecting MDCSelect to a specific field and at ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

Having issues with my project as the Three.js Scene is malfunctioning and the THREE object is not

My attempt at creating my first three.js project has hit a roadblock. After following a tutorial, I expected to see a black scene upon loading the page, but all I'm getting is a white screen. Errors in Chrome Browser Console: three.js:1 Failed to lo ...