Transform an Array of Objects into a Multi-Dimensional Array using JavaScript

Just starting out with Java Script and I have an array of objects like this:

[{
    firstName: "John",
    lastName: "Doe",
    age: 46
},
{
    firstName: "Mike",
    lastName: "Jeffrey",
    age: 56
}]

I want to transform this array of objects into a multi-dimensional array like this:

[
    [{
        firstName: "John",
        lastName: "Doe",
        age: 46
    }],
    [{
        firstName: "Mike",
        lastName: "Jeffrey",
        age: 56
    }]
]

This is the code I am using to achieve this transformation:

var actualResult = [];
var arrayLength = inputObj.length;
for (var i = 0; i < arrayLength; i++) {
    var tempResult = [];
    tempResult.push(inputObj[i]);
    actualResult.push(tempResult);
}

The variable `inputObj` represents my initial input data. Is this approach correct for what I'm trying to do?

Answer №1

To accomplish this, you can leverage the array#map method. Simply iterate through each object and construct an array.

let data = [{name: "Alice", city: "New York"}, {name: "Bob", city: "Los Angeles"}],
    result = data.map(obj => [obj]);
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

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Creating a dropdown menu within a <span> element with JavaScript

Snippet of HTML: <body onload="init();firstInit();"> Snippet of JavaScript: function init(){ var tb = new Ext.Toolbar({ renderTo: 'toolbar', height: 25 }); var ht='<table><tr>'; ht+='<td>&apo ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

Deciphering the Essence of Promise Sequences

In my NodeJS project, I am utilizing Promises and aiming to gain a better understanding of Promise.chains. Within the project, there is one exposed function: This main library function returns a promise and it is intended for users to call. After calling ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

I'm trying to figure out how to save a Mongoose query and then pass it as a parameter to render an EJS page. How can I achieve this

I'm currently in the process of constructing an admin dashboard, and one feature I want to include is displaying mongoose data such as user information and recent tutoring sessions. However, I'm facing challenges when it comes to saving this data ...

Is there a way to utilize and incorporate Functions from a separate file within an API Server file?

I have integrated ReactJS, Firebase, and React Redux into my project. https://github.com/oguzdelioglu/reactPress Currently, I am displaying data from Firestore by utilizing Functions in https://github.com/oguzdelioglu/reactPress/blob/master/src/services/ ...

Creating Canvas dimensions to match the dimensions of a rectangle specified by the user

When the code below runs, it correctly generates a rectangle the same size as the canvas on start-up. However, an issue arises when the user clicks the button to generate a new canvas - the rectangle does not appear. Can someone please provide assistance ...

What is the most effective method to determine if a given string is suitable for $compile in Angular?

I am currently in the process of creating a directive that is designed to accept a "message" input which may contain HTML and nested Angular directives. In my directive's controller, I am using the following code: var compiled = $compile(message)($sc ...

Guide to incorporating trading-vue-js into a Vue CLI project

Recently, I decided to explore the functionality of trading-vue-js and found it quite interesting. I managed to successfully run the test examples for trading-vue-js without any issues. The steps I took were as follows: nmp install trading-vue-js I then ...

"Utilizing the power of ng-click to target specific child

I am facing an issue with my owl carousel where events are not firing on cloned items. In search of a solution, I came across a suggestion from Stack Overflow to move the event handler from the direct target to its parent element: Original code snippet: ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

What is the mechanism behind $scope.$on activation and $destroy invocation?

Seeking an explanation on the functionality of $scope.$on and how $destroy works in two separate controllers. When switching routes, a new controller is invoked, leading to the activation of $destroy. Could someone shed some light on how $interval is in ...

Arranging word elements within an array using Java

I have a class called Word that stores both a word and a number. The word represents the word itself, and the number indicates how many times it appears in a string. I am looking to generate an array of words in alphabetical order, and while I know about A ...

Need assistance as require function is not functioning as anticipated

const THREE = require('three'); require('three/examples/js/loaders/OBJLoader.js'); Once I imported threejs from node_modules, I decided to utilize the provided OBJLoader, but encountered an unexpected error. THREE is not defined a ...

How can you use jQuery to transform a H3 tag into a clickable link?

To transform the h3 tag into a clickable link with jQuery and set the href attribute, while preserving the H3 styling and adding an anchor tag, you can use the following code as an example: Click Here ...

retrieving the result from an asynchronous function in Node.js

Currently, I am using Node.js to query data from Mongodb via Mongoose. Once the data is retrieved, I need to perform some operations on it before sending it back to the client. However, I am facing an issue where I cannot access the return value of the d ...

Provide the user with an .ics file for easy access

Recently, I developed an HTML5 application that enables users to download calendar entries in iCal format. These iCals are generated using PHP. Up until now, my method involved creating the iCal file with PHP and saving it to the web server's hard dis ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...