converting a multidimensional JavaScript array into an associative array

I have extracted an array from a local database and it consists of various entries.

var data = [
  ['09-08-2017', '62154', 'Approved'],
  ['09-08-2017', '62155', 'Approved'],
  ['08-25-2017', '61922', 'Approved'],
  ['08-25-2017', '61923', 'Approved'],
  ['08-18-2017', '61949', 'Approved'],
  // ...
];

There are approximately 250 different entries in this array. Each entry contains information about the date, job number, and job state.

The first element of each sub-array represents the date of the week of the job, with each week corresponding to the Friday of that week.

The second element is the job number, which is unique for each job but there can be multiple job numbers per week.

The third element represents the job state, which needs to stay associated with the corresponding job number.

My goal is to convert this array into a shifted format where all job numbers and states are grouped together based on the date:

For example:

data['09-08-2017'] = ['62154', 'Approved'], ['62155', 'Approved'];

or possibly as an object:

data['09-08-2017'] = { jobNumber: '62154', jobState: 'Approved' };

I'm unsure how to initialize this new structure or the best way to perform the conversion. Any help or advice would be greatly appreciated. Thank you!

EDIT: I discovered why the initial array was formatted strangely. When transferring an array from PHP to JavaScript, I initially used:

var data = <?php json_encode(print_r($data)); ?> ;

After further research, I changed it to:

var data = <?php echo json_encode(array_values($data)); ?>;

This not only fixed the issue but also provided a more manageable format for my array.

Answer №1

To modify the arrays, you can loop through the outer array and create new arrays based on the date values. Then add a new object to the arrays.

var data = [['09-08-2017', '62154', 'Approved'], ['09-08-2017', '62155', 'Approved'], ['08-25-2017', '61922', 'Approved'], ['08-25-2017', '61923', 'Approved'], ['08-18-2017', '61949', 'Approved']],
    object = data.reduce(function (r, a) {
        (r[a[0]] = r[a[0]] || []).push({ jobNumber: a[1], jobState: a[2] });
        return r;
    }, Object.create(null));

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

In JavaScript, there are no "associative arrays," only objects and the Map data structure introduced in ES2015.

If you want to transform an array of arrays into an object where each date corresponds to a set of job numbers and states, you can achieve this by creating empty objects using curly braces like so:

var obj = {};

You can then populate these objects with the appropriate information as follows:

obj["09-08-2017"] = {};

To add job numbers and states for each date, you can use object initializers:

obj[entry[0]] = {
    jobNumber: entry[1],
    jobState:  entry[2]
};

However, keep in mind that having multiple entries for the same date may not be feasible with this structure. A possible alternative could look something like this:

{
    "08-09-2017": {
        12345: "Approved",
        67894: "Approved"
    }
}

Here's an example illustrating how you can organize your data:

var data = [
    ["09-08-2017", 62154, "Approved"],
    ["09-08-2017", 12345, "Approved"],
    ["08-08-2017", 62155, "Approved"]
];
var obj = {};
data.forEach(function(entry) {
    var date = entry[0];
    if (!obj[date]) {
        obj[date] = {};
    }
    obj[date][entry[1]] = entry[2];
});
console.log(obj);

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

Ordering tables in Knockout.js based on either values or alphabetically

I have a dataset in tabular form and I've implemented a knockout binding handler for sorting the table data upon clicking. The current functionality sorts the values, but I need to enhance it to sort groups of data with the same value alphabetically b ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

AngularJS is restricting the use of square brackets within the URL parameter, specifically the character '[.'

My goal is to connect to an external API Everything works smoothly when my parameters are set up like this $http.post('http://api.myprivatebox.com/users.json', { email : email, password : password}).then(function (results) { console.log( ...

Invoke Selenium using JavaScript

Imagine I have this (fictional) JavaScript snippet: asynchronousOperation.addEventListener("completed", function (event) { if (event.property == "required value") tell Selenium we are good; else tell Selenium the test failed; }); ...

Utilize Bootstrap accordions nesting inner accordions to create a dynamic user interface with varying shown.bs.c

I am currently dealing with a nested bootstrap accordion issue. The problem arises when I click on the inner accordion - it unexpectedly triggers the 'shown.bs.collapse' event bound to the outer accordion, which is not the intended behavior. Is t ...

Tips for extracting data from various select drop-down menus within a single webpage

As a newcomer to JQuery, I apologize if this question seems basic. I have a page with 20 categories, each offering a selection of products in a drop-down menu. The user will choose a product from each category, triggering an ajax call to retrieve the pric ...

Issues with receiving data on $.ajax POST request

If you'd like to check out my website Please use the following login details (case sensitive): Username: stack Password: stack Click on the tab labeled "yourhours." The main goal is to send all input box data to a database. At the moment, I am fo ...

Matching the characters '/#' in a href can be achieved by using regular expressions

I am using the following code to check if the href attribute starts with # and based on that add a class: $('.navbar-nav a').each(function(index, element) { if($(element).attr("href").match("^#")) { //Add class to internal links ...

Using jQuery UI Dialog with pjax for dynamic content loading

I'm currently utilizing pjax within a web application that incorporates jQuery UI dialogs. One issue I've encountered is that the div element responsible for creating the dialog gets displaced from its original container in the DOM once the dialo ...

What is the method for removing specific bytes from a byte array in C programming?

If I have a byte array called buff with a length of n: unsigned char buff[n] = "....." // len n I need to remove m characters from position pos, 0 < pos, m, pos + m < n I attempted to delete them using the memmove function: memmove(buff ...

What steps can I take to avoid redirection after submitting form data in express.js?

Is there a way to prevent a redirect on an AJAX call in Express? I've tried using the "return false" method, but it doesn't seem to be working. How can I manage redirection after submitting data? The code below is functioning correctly, but it re ...

Issue with CasperJS: The function this.waitForUrl is not defined and is causing an error

My casperJS script handles form filling, however I encountered the following error message: A TypeError occurred: 'undefined' is not a function (evaluating 'this.waitForUrl') I suspect this might be an issue with using an outdated ver ...

Leveraging Ajax to enhance the functionality of datatables

I am currently working with a datatable in my project, but I'm facing difficulty in retrieving data from my ajax file to the datatable codes. Below are the snippets of my codes: AJAX <?php function functionClass($id) { // create sql query ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

What could be the reason for receiving a Firebase INVALID_DYNAMIC_LINK_DOMAIN error message?

I'm having trouble implementing email verification in my React website. Whenever I use the sendSignInLinkToEmail function, I encounter the following error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx [ ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Another option for document.execCommand('selectAll',false,null)

I've come across a piece of code that allows me to select the text in a div whenever a user clicks on it: <table> <tr> <td> <div contenteditable onClick="document.execCommand('selectAll',false,null)">I& ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

What is the method for assigning memory to a zero-length nested array?

Looking to create a struct called Ring with a nested zero-length array: typedef struct Data_Block { size_t Data_Len; char Buf[0]; }Block; typedef struct Block_Ring { int head; int tail; int full; int block_num; B ...