Exploring the depths of nested arrays in JavaScript

Struggling to convert the given array into object properties using nested array notation: array[x][y]

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];

function fromListToObject(array) {
  var result = {};
  for(var i = 0;i < array.length;i++){
    console.log(array[i]); // checking output
    for(var j = 0;j < array[i].length;j++){
      console.log(array[i][j]); // checking output
      console.log(array[i][j+1]); // checking output
      result[array[i][j]] = array[i][j+1];
    }
  }
  return result;
}
fromListToObject(array);

Current Output:

[ 'make', 'Ford' ] //inner array
make               //key
Ford               //value
Ford               //unexpected
undefined
[ 'model', 'Mustang' ]
model
Mustang
Mustang
undefined
[ 'year', 1964 ]
year
1964
1964
undefined
=> { '1964': undefined, //Issue here?
  make: 'Ford',         //Correct!
  Ford: undefined,
  model: 'Mustang',
  Mustang: undefined,
  year: 1964 }

I did manage to solve this with forEach:

function fromListToObject(array) {
  var result = {};
  array.forEach(function(element){
    result[element[0]] = element[1];
  });
  return result;
}

and I can capture the inner array into a temporary variable too. Seeking guidance for improvement. Thanks.

EDIT

Appreciate the help provided. Learners like me need such guidance.

Answer №1

The error is occurring because you are trying to access an index that does not exist

Give this solution a shot

var data = [['type', 'Fruit'], ['name', 'Apple'], ['color', 'Red']];

function convertListToObject(data) {
    var output = {};
    for (var x = 0; x < data.length; x++) { 
        for (var y = 0; y < data[x].length-1; y++) { // Update the condition here 
            output[data[x][y]] = data[x][y + 1];
        }
    }
    return output;
}
convertListToObject(data);

Answer №2

The use of the .forEach() method is recommended as it provides a clear and efficient solution. If traditional loops are preferred, there is no need for a nested loop. By iterating through the main array, each pair can be assigned with a single operation. Here's an example:

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

Answer №3

To achieve the same outcome as your previous foreach solution, it is recommended that you follow a similar approach.

Simply omit the unnecessary

for(var j = 0;j < array[i].length;j++){
loop for better clarity and efficiency.

Incorporate the usage of array[i][0] and array[i][1] just like in your previous foreach implementation.

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 persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Use map.fitBounds in MapBox to continuously adjust the map view to show only the visible features on the map

In my map, there are various features with IDs stored in an array called featureIds. Within my application, I have a button that can toggle the visibility of certain features. To address this toggling behavior, I am developing a JavaScript function named ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

How to retrieve a nested array element in JavaScript

Here is the Pastebin link of the index.html file for reference: http://pastebin.com/g8WpX6Wn (The file contains broken image links and no CSS styling). If you would like to access the entire project, you can download the zip file. I am currently working ...

What is the best way to reset a 2D array in Java and how can I safely create a backup of my 2D

Is there a way to backup my 2D array? How can I remove all elements from the array? int numberArray[][]= new int[4][5]; ...

Display the items in the list according to the element's x and y coordinates, which must be whole numbers

I have a collection of unique "blocks" with coordinates (x,y). The x and y positions are integers without duplicates, and the collection is unsorted. My goal is to display these blocks based on their coordinates. What would be the best approach for this? ...

if considering an integer value of 0 as equivalent to null

I am struggling with using axios to send data to an API in react. Despite the server successfully receiving the values, my code is not entering the if block as expected. Interestingly, when I make the same request from a rest client, it works perfectly. He ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Having trouble storing the message ID within the user Object using Mongoose

My goal is to add a message to the messages property (an array) of a user object using Mongoose. However, I encounter an error when trying to save the user (user.save()). To troubleshoot, I added three console.log statements in the code below. Can anyone h ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Transforming a high chart into an image and transmitting it to the server through an ajax request

I am looking for a way to save multiple charts as PDF files on the server using an AJAX call. Each chart is rendered in a distinct container on the same page, and I need to convert them into images before sending them to the server for export. Any assist ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure. This particular file is my employeeController.js (function() { angular.module('employeeApp').controller('employeeController', employeeCont ...

Trouble with Fetch in JS and PHP not sending parameters

Having trouble getting a PHP function to accept data from JavaScript, despite the PHP class working elsewhere in the application. The getTopFive() function works fine, but data insertion isn't happening as expected. Below is the code snippet along wit ...

What is the best way to separate an array of numbers into individual digits using JavaScript?

I am looking to transform an array const myArr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ] into a new array with digits split like this: const splited = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1, 0, 2, 1, 0, 3, 1, 0, ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...