Merge arrays to form nested structures

Here's a mind-bending scenario for you.

Imagine I have two arrays - one containing categories and the other containing arrays that follow the structure of those categories. For example:

var categoryArray = ["Name", "Title", "Hire Date"];
var infoArray = [["John","Project Manager","January 5"], ["Alex","Accountant","December 15"], ["Joanne","Graphic Designer","August 26"]];

I want to combine this data into a single object. To start off, I create an empty object like so:

var myDict = {};

I attempted to achieve this using nested for-loops, trying to populate myDict with the array contents. Here's what I tried:

// Loop through each entry in the infoArray
for (i = 0; i < infoArray.length; i++) {
    var row = String("row"+i);
    myDict.row = {};
    // Loop through each category
    for (x = 0; x < categoryArray.length; x++) {
        myDict.row.categoryArray[x] = infoArray[i][x];
    }
}

Clearly, there are many mistakes here, and I'm stuck on how to fix them. The main issue seems to be using variables/arrays as names for objects. Any help from the all-knowing internet would be greatly appreciated!

Answer №1

let newData = infoArray.map(function(currArr) {
    return categoryArray.reduce(function(prev, currKey, index) {
        prev[currKey] = currArr[index];
        return prev;
    }, {});
});

Data Output

[ { Name: 'John',
    Title: 'Project Manager',
    'Hire Date': 'January 5' },
  { Name: 'Alex',
    Title: 'Accountant',
    'Hire Date': 'December 15' },
  { Name: 'Joanne',
    Title: 'Graphic Designer',
    'Hire Date': 'August 26' } ]

If your tool does not support Array.prototype.map method, you can utilize this alternative:

let newData = [];
for (let i = 0; i < infoArray.length; i += 1) {
    let tempObject = {};
    for (let j = 0; j < categoryArray.length; j += 1) {
        tempObject[categoryArray[j]] = infoArray[i][j];
    }
    newData.push(tempObject);
} 

Answer №2

Instead of using row0, row1, etc., it would be better to utilize an array for a more organized approach. Here is an example:

var categoryArray = ["Name", "Title", "Hire Date"];
var infoArray = [["John","Project Manager","January 5"],["Alex","Accountant","December 15"],["Joanne","Graphic Designer","August 26"]];
var myDict = {};

for (i = 0; i < infoArray.length; i++) {
    var row = {};
    myDict["row"+i] = row;
    
    for (x = 0; x < categoryArray.length; x++) {
        row[categoryArray[x]] = infoArray[i][x];
    }
}

Generated Output:

{
    "row0": {
        "Name": "John",
        "Title": "Project Manager",
        "Hire Date": "January 5"
    },
    "row1": {
        "Name": "Alex",
        "Title": "Accountant",
        "Hire Date": "December 15"
    },
    "row2": {
        "Name": "Joanne",
        "Title": "Graphic Designer",
        "Hire Date": "August 26"
    }
}

Answer №3

// It seems like the declaration below does not assign "Row1", "Row2", etc as nested objects as intended, but instead rewrites a child called "row"
myDict.row = {};

Indeed. To achieve that, you need to use

 myDict[row] = {};

(and similarly below: myDict[row][…] = …)

// The initial run of this will create a child of "row1" named "name," storing the value "John" (equivalent to infoArray[1][1])
myDict.row.categoryArray[x] = infoArray[i][x];

Once again, using .categoryArray[x] implies a literal property name (the property x of the non-existent property "categoryArray") - wrapping it in brackets is necessary.

Your final code should be:

var myDict = {};
for (var i = 0; i < infoArray.length; i++) { // declaring iteration variables locally
    var row = "row"+i;
    myDict[row] = {};
    for (var x = 0; x < categoryArray.length; x++) {
        myDict[row][categoryArray[x]] = infoArray[i][x];
    }
}

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

Node.js retrieves values through the app.get and app.post methods

In my project, I'm utilizing the app.get and app.post functions in Express on Node.js. Below is an example of how I have used the app.post function: app.post('/status', function(req, res) { if (~packages.STATUSES.indexOf(req.body['s ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

AngularJS Filter without creating a new object

Within my code, I am dealing with an array of objects that contain sub-objects. This particular array is utilized in an ng-repeat to display data in a table format. To illustrate, consider the following example: device { "name": "computer" ...

Can grapesjs be integrated into AngularJS using a controller?

JavaScript Question var app = angular.module('CompanyProfile', []); app.controller('CompanyProfileCtrl', function() { function initializeEditor() { var editor = grapesjs.init({ allowScripts: 1, ...

How to effectively utilize signed requests for AWS S3 when uploading images?

My project involves developing a react native application similar to Slack, and I'm currently facing an issue with image uploads to S3. I decided to use the getSignedUrl route for this functionality. The process goes as follows: the client selects a ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

The Angular carousel fails to display or operate properly

I am encountering an issue where the content is not displaying when using the angular-carousel directives: <ul rn-carousel rn-carousel-controls rn-carousel-index="carouselIndex" rn-carousel-buffered > <li ng-repeat="slide in slides track by ...

jQuery Autocomplete API Issue: Undefined

I've been attempting to implement a basic text box using the jQuery API from DevBridge. I followed instructions in this video tutorial to create my code. However, despite properly declaring scripts before the JS code and ensuring proper mappings, I&a ...

What is the best way to hand off slots to a descendant component in Vue 3?

Is it possible to have a component within a 'layout' component populate its slots? JS Fiddle <div id="app"> <layout> <page></page> </layout> </div> const app = Vue.createApp({}); ap ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

Update the path dynamically in Next.js without the need to reload the page

Every time the user clicks on the continue button, a function is triggered. Within that function, I make the following call: push("/signup/page-2", undefined, { shallow: true }); All dynamic routes resembling /signup/[page].js that return <Component / ...

Tips for eliminating white spaces when text wraps onto a new line

Imagine having the following code snippet. Essentially, I have a layout that needs to display 'vs prev period' with a percentage in the same line. To achieve this, I utilized display: flex. The issue arises when we require the gap between the tw ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

A guide to managing Ajax in functional components in React without using classes

Currently, I am striving to develop all my components as pure functions. However, I have encountered an issue. The component I am working on resembles the structure below. The problem arises when the result of an ajax request triggers a rerender, leading ...

A more efficient way to have Vue import files from the assets folder rather than manually inserting script tags into the index.html file

I have a simple structure and would like to utilize assets from cdnjs.com in my project. The issue arises when I try to import these assets from src/assets/lib instead of directly from the CDN. For example, importing jQuery like this: Main.js: import &a ...

Importing named exports dynamically in Next.js

Currently, I am in the process of learning Next.js and I want to utilize a function called getItem from the package found at https://www.npmjs.com/package/encrypt-storage In my attempt to do so using the code snippet below, I encountered an error stating ...