简体   繁体   中英

Programmatically creating a dictionary from a large 2D array in Javascript

I have an 2D array (in Javascript), RED with four elements, each of which has another four elements (the parts outside the brackets aren't part of the array, just labels).

          Ab  Cd  Ef  Gh
 Red1   [['1','2','3','4'],
 Red2    ['4','3','2','1'],
 Red3    ['5','6','7','8'],
 Red4    ['8','7','6','5']]

And I need to convert this into a labeled dictionary (I'm trying to send this through AJAX using jQuery to a Flask Python file.) So basically I want a dictionary that looks like

{red1_ab: 1, red1_cd: 2, red1_ef: 3, red1_gh: 4, red2_ab: 4 ...}

How can I do this without creating 16 variables manually? Or is there a way to send a 2D array through jQuery $.getJSON?

For reference, my AJAX call is below (in Javascript).

$(function() {
    $('#btn-send-email').click(function() {
        $.getJSON('http://www.example.com/email', {
            exone: example[0],
            extwo: example[1],
            [dictionary objects from array RED go here]
        })
    })
})

Thanks.

Well here's a way to do the structure conversion with a simple for loop or two:

var RED = [['1','2','3','4'],
           ['4','3','2','1'],
           ['1','2','3','4'],
           ['4','3','2','1']],
    dictionary = {},
    letters = "abcdefghijklmnopqrstuvwxyz",
    i,
    j;
for (i = 0; i < RED.length; i++)
    for (j = 0; j < RED[i].length; j++)
        dictionary["red" + (i+1) + "_" + letters.substr(j*2,2)] = RED[i][j];

Or instead of using just a string letters you could define the "x axis" labels in an array:

    x = ["ab","cd","ef","gh"],

...and then:

    dictionary["red" + (i+1) + "_" + x[j]] = RED[i][j];
function objectFromMatrix(matrix, rowNames, columnNames) {
    var obj = {};
    for(var i = 0; i < matrix.length; i++) {
        var currentRow = matrix[i],
            rowName = rowNames[i];
        for(var j = 0; j < currentRow.length; j++) {
            var columnName = columnNames[j];
            obj[rowName + "_" + columnName] = currentRow[j];
        }
    }
    return obj;
}

var RED = [['1','2','3','4'],
           ['4','3','2','1'],
           ['5','6','7','8'],
           ['8','7','6','5']];

objectFromMatrix(RED, ["red1", "red2", "red3", "red4"], ["Ab", "Cd", "Ef", "Gh"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM