What is the best way to transform an array that contains arrays into an array that contains objects with newly-defined properties?

Is there a way to transform this: [[a1, b1], [a2, b2]] into this format?

[{x1: a1, y2: b1}, {x2: a2, y2: b2}]
?

Please note that the properties x1 and x2 are newly introduced with values a1, b1, etc.

I attempted to achieve this with the following code snippet:

formatData.map((data, index) => {
  const obj = {
    dataX: data[index][0],
    dataY: data[index][2]
  }
  data = obj
}

However, I encountered a roadblock in the process.

Answer №1

Using a basic for loop to achieve the desired result

var data = [["key1", "value1"], ["key2", "value2"]];
var result = [];
var keys = ['a','b','c'];//...
for(var i in data){
  var obj = {};
  for(var j in data[i]){  
    obj[keys[j]+(parseInt(i)+1)] = data[i][j];
  }
  result.push(obj);
}
console.log(result);

Answer №2

To utilize the array mapping method, you can follow the example code snippet below

var data = [['apple', 'red'], ['banana', 'yellow']];

data.map(function(item,index){
   var result = {};
   result['key'+(index+1)]= item[0];
   result['value'+(index+1)]= item[1];
   return result;
});

//Output: [{"key1":"apple","value1":"red"},{"key2":"banana","value2":"yellow"}]

Answer №3

Utilize the `forEach` method

var array = [
  ['a1', 'b1'],
  ['a2', 'b2']
];
var temp = []
array.forEach(function(item, index) {
  var obj = {};
  obj['x' + 1] = item[0];
  obj['y' + 1] = item[1];
  temp.push(obj);
})

console.log(temp)

Answer №4

To create new objects, you can utilize mapping of values and utilize the Object.assign method.

var keys = ['x', 'y'],
    data = [['a1', 'b1'], ['a2', 'b2']],
    result = data.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));
    
console.log(result);

You can specify the keys and corresponding indices in an object.

var keys = { x: 0, y: 2 },
    data = [['a1', 'b1', 'c1'], ['a2', 'b2', 'c2']],
    result = data.map(a => Object.assign(...Object
        .keys(keys)
        .map(k => ({ [k]: a[keys[k]] }))
    ));
    
console.log(result);

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

There was a serious issue: The mark-compacts were not working effectively near the heap limit, resulting in allocation failure - the JavaScript heap ran out of memory during the

I recently set up a t2.micro server on AWS and encountered an issue when running our application with the command "sudo npm start". The error message I received was: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript he ...

AngularJS: How to accurately retrieve the offsetTop value upon page initialization

Issue: I am facing difficulty in obtaining the accurate top offset value of a DOM element immediately after the page has loaded. In the project I am currently working on, it is essential to retrieve the offsetTop value of various DOM elements as soon as ...

A guide on incorporating a Java loop with Selenium automation

// Searching and deleting process driver.findElement(By.cssSelector("input[type='search']")).sendKeys("Diversification Rule Template"); driver.findElement(By.className("delete-template")).click(); Alert alert = driver.switchTo.alert(); Thread. ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Developing HTML5 animation by utilizing sprite sheets

Struggling to create an engaging canvas animation with the image provided in the link below. Please take a look at https://i.stack.imgur.com/Pv2sI.jpg I'm attempting to run this sprite sheet image for a normal animation, but unfortunately, I seem to ...

React - Received an unexpected string containing a template expression with no curly braces present in the string

Currently, I am enrolled in a React tutorial online. I have inputted the code exactly as it was shown on the screen. Strangely, it seems to be working perfectly fine in the video but not when I try it myself. Below is the code snippet: <Link to={&apos ...

JavaScript for creating dropdown menus using Twitter Bootstrap

I've been struggling to get the dropdown menus in my Twitter Bootstrap project to function properly. Below is the code I have for the navbar: <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> < ...

Guide to using jQuery to load an image

I am using this code to load an image and display it within a dialog box. <div id="image_preview" title="Client Photo Preview"> <p><img src="" alt="client image" id="client_image_preview" /></p> </div> $("#client_image_p ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

The function is attempting to access the 'lockDatabase' property of an undefined object, resulting in an error

I'm encountering an error due to the scope issue with 'this', and I'm struggling to find a solution. I attempted using the fat arrow, which solved the scope problem but created another issue where I lack a callback value that needs to b ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...

Leveraging personalized AngularJS directives in conjunction with ExpressJS routing

I built my own AngularJS application following a tutorial at . However, I encountered an issue when trying to integrate it with an ExpressJS/Node backend. The tutorial only covers a single view with a single controller, while my Angular app includes multip ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

What is the process for interacting with DOM Elements in Node JS?

JAVASCRIPT FILE const path = require('path'); const http = require('http'); const fs = require('fs'); const dir = '../frontend/'; const server = http.createServer((request, respond) => { console.log(reques ...

Passing a variable to a different PHP script

I'm facing a dilemma and need some assistance. I'm encountering an issue where a PHP variable (or JavaScript/jQuery) is not being successfully transmitted to another PHP file through an AJAX request that I set up. To provide context, I am in the ...

I am currently focusing on using websockets in combination with JavaScript and Golang servers to efficiently transmit files and

When front-end JavaScript websockets send a JSON object, it looks something like this: message_type: "1" to: "umesh" from: "moin" body: "" file: "{"filename":"reportesmtp.pdf" ,"fileextension":"application/pdf" ,"filesize":61813 ,"filedata ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Uncovering unseen tags generated by JavaScript on a webpage using Python

I have THIS LINK page that contains javascript. To view the javascript, simply click on show details. How can I extract data from this URL source? Should I use re? Here is what I attempted with re: import urllib import re gdoc = urllib.urlopen('Tha ...