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

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

我想在 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
3个回答
1
投票

问题是您没有使用 reduce() 函数在代码中创建所需的结构。

要获得您在评论中描述的输出,根本不需要循环。您可以创建一个具有指定结构的新对象:

const 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],
];

const [identifiers, values] = totals;
const result = {
  totals: [{
    identifier: identifiers,
    values: values,
  }]
};

console.log(JSON.stringify(result, null, 4));
/* Stackoverflow: show only console */
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

我在这里使用数组解构。相反,您还可以使用索引来访问数组。

如果你想确保不变性(尽管你没有在这里编写/更改任何内容),你当然也可以复制数组,例如通过使用 spread 语法,如

[...identifiers]
(或使用
identifiers.slice()
),然后引用新对象中的副本。

仅供参考:如果数组中只有一个条目,我不确定为什么您希望

totals
成为一个数组(或者为什么它甚至是复数形式)。您可以轻松地将其变成一个对象。


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]
    } };

0
投票

为了生成您愿意的输出,您不必使用

reduce()
函数

只需使用以下代码:

var totalsObj = {
    totals: [{
        identifier: totals[0],
        values: totals[1]
    }]
};

finalJsonString = JSON.stringify(totalsObj,null,4);

你的最终代码应该是这样的:

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],
    ];
    /* updated code */
    var totalsObj = {
        totals: [
            {
                identifier: totals[0],
                values: totals[1],
            },
        ],
    };

    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);
}

就是这样。

© www.soinside.com 2019 - 2024. All rights reserved.