简体   繁体   English

通过Java中的大型2D数组以编程方式创建字典

[英]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). 我有一个2D数组(使用Javascript),带有四个元素的RED ,每个元素都有另外四个元素(方括号之外的部分不是数组的一部分,只是标签)。

          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 我需要将其转换为带标签的字典(我正尝试使用jQuery通过AJAX将其发送到Flask Python文件。)因此,基本上,我想要一个看起来像这样的字典

{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? 如何在不手动创建16个变量的情况下执行此操作? Or is there a way to send a 2D array through jQuery $.getJSON? 或者有没有办法通过jQuery $ .getJSON发送2D数组?

For reference, my AJAX call is below (in Javascript). 作为参考,下面是我的AJAX调用(使用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: 好了,这是使用一两个简单的for循环进行结构转换的方法:

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: 或者,不只是使用字符串letters还可以在数组中定义“ x轴”标签:

    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"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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