Converting Arrays into Objects with Multiple Dimensions

I have been attempting to transform this complex array into an object. However, I am facing an issue where only the second part of the array is being saved in the object, while the first part is missing.

Is there a way to ensure that the entire array gets stored in the object?

var data = [
  [
    ['name', 'John Smith'],
    ['age', 34],
    ['occupation', 'nurse']
  ],
  [
    ['name', 'Nico Klein'],
    ['age', 24],
    ['occupation', 'engineer']
  ]
];

function convertToObject(arr) {
  var obj = {};
  for (var j = 0; j < arr.length; j++) {
    for (var i = 0; i < arr[j].length; i++) {
      obj[arr[j][i][0]] = arr[j][i][1];
    }
  }
  return obj;
}

var finalResult = convertToObject(data);

console.log(finalResult);

Additionally, are there more efficient ways to write this conversion code?

Answer №1

You've made a good effort, but the parent should actually be an array of objects for better organization.

var array = [
  [
    ['name', 'John Smith'],
    ['age', 34],
    ['occupation', 'nurse']
  ],
  [
    ['name', 'Nico Klein'],
    ['age', 24],
    ['occupation', 'engineer']
  ]
];

function toObject(arr) {
  var obj = [];
  for (var j = 0; j < arr.length; j++) {
    var cur = {};
    for (var i = 0; i < arr[j].length; i++) {
      cur[arr[j][i][0]] = arr[j][i][1];
    }
    obj.push(cur);
  }
  return obj;
}

var result = toObject(array);
console.log(result);

The resulting output will follow this order:

[
  {
    "name": "John Smith",
    "age": 34,
    "occupation": "nurse"
  },
  {
    "name": "Nico Klein",
    "age": 24,
    "occupation": "engineer"
  }
]

All records from the original array are maintained in this conversion. If you wish to transform the resulting array into an object, refer to Convert Array to Object.

var array = [
  [
    ['name', 'John Smith'],
    ['age', 34],
    ['occupation', 'nurse']
  ],
  [
    ['name', 'Nico Klein'],
    ['age', 24],
    ['occupation', 'engineer']
  ]
];

function toObject(arr) {
  var obj = [];
  for (var j = 0; j < arr.length; j++) {
    var cur = {};
    for (var i = 0; i < arr[j].length; i++) {
      cur[arr[j][i][0]] = arr[j][i][1];
    }
    obj.push(cur);
  }
  return obj;
}

var result = toObject(array);
var resObj = result.reduce(function(acc, cur, i) {
  acc[i] = cur;
  return acc;
}, {});
console.log(resObj);

The final Object output is as follows:

{
  "0": {
    "name": "John Smith",
    "age": 34,
    "occupation": "nurse"
  },
  "1": {
    "name": "Nico Klein",
    "age": 24,
    "occupation": "engineer"
  }
}

Answer №2

To start with, consider transforming the array into an "array of objects", especially since it contains two elements. It would make more sense to work with an array of objects in this case.

Furthermore, while the program is on the right track, there seems to be a mistake. Upon reviewing your code, you'll notice that you have initialized a var obj = {};, which assigns object properties rather than creating an array of objects. To rectify this issue, modify the function as shown below:

function convertToObject(arr) {
  var arrayOfObjects = [];
  for (var j = 0; j < arr.length; j++) {
    var currentObj = {};
    for (var i = 0; i < arr[j].length; i++) {
      currentObj[arr[j][i][0]] = arr[j][i][1];
    }
    arrayOfObjects.push(currentObj);
  }
  return arrayOfObjects;
}

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

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

What is the purpose of the .Class method in ng.core.component within ES5?

ng.core.Component({ selector:'myapp', template:'<h1>Hello World</h1>' }). Class( { constructor:function() } ); ...

Gather information from various mongodb collections and consolidate them into a single array using Javascript

Is there a way to retrieve the most recent item from multiple collections and store them in an array based on the collection name and newest item? How can I accomplish this either sequentially or asynchronously? let dat = ["test", "test2"]; ...

React component not displaying HERE map controls

Having trouble implementing zoom in and zoom out controls on HERE maps in React. Despite following the documented steps, I am unable to find a solution. I have meticulously followed all instructions provided at: The link to my map component can be found ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

Utilizing Sinon.js for inline callbacks upon successful execution

Currently, I am utilizing QUnit, Sinon.js (specifically fakeServer), and jQuery (for AJAX) to capture and test AJAX calls within my program. One issue that I am encountering pertains to the inconsistency where inline-function calls are not being executed. ...

Saving the AJAX response object in a global variable - Important fields are not being retrieved

Currently, I am developing an asynchronous webpage in Grails wherein I invoke a controller and display the response as a D3.js network. To ensure further usability, I saved the object as a global variable. Despite the successful execution of the function u ...

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

What is the reason for the binding event being triggered following the re-render of the setstate?

The Test component has a state of num. This component is designed to increase the value of num by 1 when a button is clicked. The button is linked to a self-increment method, and the keyup event is also connected to this method. When the method is triggere ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...

Transferring an array of objects from one array to another with the click of a button

I'm facing an issue with moving data between two arrays of objects using buttons in a Nextjs project. The functionality works correctly when selecting a single data item, but it gives unexpected results when selecting multiple items. Although my code ...

Variations in ajax requests coupled with a polling mechanism

Suppose the initial ajax call is made right away, and the function called by the controller keeps looping until it reads something, as shown below: def FirstAjax(): while True: if something is read: val = something brea ...

Embarking on a New Project with Cutting-Edge Technologies: Angular, Node.js/Express, Webpack, and Types

Recently, I've been following tutorials by Maximilian on Udemy for guidance. However, I have encountered a roadblock while trying to set up a new project from scratch involving a Node/Express and Angular 4 application. The issue seems to stem from the ...

Implementing a JQuery modal with backend coding

I have encountered a problem in my ASP.NET code-behind where I am trying to incorporate a modal popup. Despite my efforts, I have not been able to successfully implement it. Do you have any suggestions on how I should proceed with this process? <scrip ...

Assistance with Ajax for content loading

Greetings, I am encountering an issue with the following code snippet (located in a js file named ajax.js) $(function(){ $("#loading").hide(); $("ul#nav a").click(function(){ page = "content/"+$(this).attr('href') ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

SyntaxError: The input on line one ended unexpectedly and was not caught

This issue is commonly associated with messy close parentheses, however, the error is occurring on line 1 of the file! Below is the javascript code from (filename: calculate.js) var colors = new Array(); colors["SILVER"] = -2; ... Although there is m ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...