如何使用java脚本将二维数组保存在json文件中?

问题描述 投票:0回答:1

我想在 json 格式的文件中保存一个由一列指标(字符串)和一列值(双精度整数)组成的二维数组。它以某种方式起作用,但不是我最终想要的方式。我不明白为什么我得到两次结果的问题。有什么想法吗?我在网上搜索了好几天,但还没有找到任何有帮助的答案 - 或者我不明白答案。是的,它是客户端。

该功能目前如下所示:

function array2JSON(fname) {

    var totals = [
        ["ID_1", "ID_2", "ID_3", "ID_4", "ID_5","ID_6","ID_7","ID_8"],
        [171.82, 54.0, 2.33, 1234.2, 1.23, 45.67, 0.98,0.123]
    ]; 
    
    var totalsObj =  totals.reduce((map, totals) => { 
        
        
        map.totals.push(  {identifier: totals, values: totals}); 
        
        
        return map;
    }, { totals: []});

    var myBlobFile = new Blob([JSON.stringify(totalsObj,null,4)], { 
       type: 'text/json;charset=utf-8' 
    });
    
    var url = window.URL || window.webkitURL;
    
    var temp_link = document.createElement('a');
    temp_link.download = fname+".json";
    temp_link.href = URL.createObjectURL(myBlobFile);
    //temp_link.hidden = true;

    

    // This link should not be displayed
    
    document.body.appendChild(temp_link);
    temp_link.click();
    document.body.removeChild(temp_link);
}

我得到的是这样的:

{
    "totals": [
        {
            "identifier": [
                "ID_1",
                "ID_2",
                "ID_3",
                "ID_4",
                "ID_5",
                "ID_6",
                "ID_7",
                "ID_8"
            ],
            "values": [
                "ID_1",
                "ID_2",
                "ID_3",
                "ID_4",
                "ID_5",
                "ID_6",
                "ID_7",
                "ID_8"
            ]
        },
        {
            "identifier": [
                171.82,
                54,
                2.33,
                1234.2,
                1.23,
                45.67,
                0.98,
                0.123
            ],
            "values": [
                171.82,
                54,
                2.33,
                1234.2,
                1.23,
                45.67,
                0.98,
                0.123
            ]
        }
    ]
}
javascript arrays json client-side
1个回答
0
投票

你的代码故意构建了你最终得到的结构。

.reduce()
调用将调用回调两次,针对二维
totals
数组的每一行调用一次。第一次调用时,参数“totals”的值将是外部
totals
二维数组的“ID”行。在第二次通话时,它将是第二行,带有数字。

所以回调:

(map, totals) => { 
    map.totals.push(  {identifier: totals, values: totals}); 
    return map;
}

将参数“totals”的值添加到对象两次。第一次,您得到一个带有“ID”字符串的对象(两次),第二次您得到一个带有数字的对象(两次)。

你的问题没有解释你想要什么,但是如果(例如)你想要一个像这样的数组:

[
    ["ID_1", 171.82],
    ["ID_2", 54],
    // ...
]

然后你可以通过一个简单的循环轻松实现:

    let result = [];
    for (let i = 0; i < totals[0].length; i++)
        result.push([totals[0][i], totals[1][i]]);
从您添加的评论中

编辑,这要容易得多:

    let result = { totals: {
        identifier: totals[0],
        value: totals[1]
    } };
© www.soinside.com 2019 - 2024. All rights reserved.