首页 > 解决方案 > 如何在循环中将 JSON 元素分配给二维数组

问题描述

我正在尝试将 JSON 对象中同一级别的两个项目(用户 ID、数量)分配到 JSON 对象中每个用户 ID 的 2D 数组中(假设该对象有 10 个用户 ID,因此 2D 数组应该有 10 行用户 ID 作为第 0 列,金额作为第 1 列):

JSON
    {"page":"1",
     "per_page":10,
     "total":100,
     "total_pages":10,
     "data":[{"id":1,
              "userId":1,
              "userName":"Jim Silver", 
              "timestamp":16425382171,
              "txnType":"debit",
              "amount":"$1,000.07",
              "location":{"id":2,
                          "address":"654, Somewhere, Some Street", 
                          "city":"Some City",
                          "zipCode":12345},
                          "ip":"202.210.105.105"},
          {"id":2," ...}

结果应该是(金额转换为整数和 Math.Floor 应用):

[1, 1000] // User ID = 1, corresponding amount = 1000
[2, 2000] // User ID = 2, ...
[3, 3000]
[4, 4000]
...

我用描述 JSON 对象中三个级别的三个类对我的 JSON 建模。

我已经声明了一个二维数组: int[,] userTxnsArr = new int[1, model.data.Count];(10 行,2 列)

现在循环遍历模型中的反序列化 JSON 对象:

for (int datum = 0; datum < model.data.Count; datum++)
{
    userID = model.data[datum].id;
    userAmount = Convert.ToInt32(Math.Floor(decimal.Parse(model.data[datum].amount, System.Globalization.NumberStyles.Currency)));
    userTxnsArr = new int[,] { { userID, userAmount } };
}

但我只得到二维数组中的最后一条 JSON 记录(所以只有一行数据)。如何将每个 JSON 记录分配到二维数组的每一行?提前致谢。

标签: arraysjson2d

解决方案


我感觉缺乏这方面的信息,所以我会在这里或那里推断出一些东西。

我假设:

  • 你有你的所有信息"page": "1"
  • 您使用的语言可以是 javascript
  • 如果这不是您想要的语言,由于语言性质,算法将非常相似

我冒昧地创建了一些变量来简化一些事情,然后......当我说jsonData,嗯......它是你的 JSON 数据,这里没有奇迹。

我使用 nodejs 对其进行了测试,只是为了看不到 JSON,但它也可以在现代浏览器中工作(直接分配 JSON 数据)

// Imagine your shining-beautiful JSON here
const jsonData = require('./data.json');

// This is your "JSON page 1" data field (array of things)
const elements = jsonData.data;

// Write your helper to convert the "amount" string into something you need
function convertAmount(rawAmount) {
        // Your amount parser should come here (currency string -> the int you want)
        // I'm just returning directly, you may change it to use
        return rawAmount;
}

// This.... is the 2D Array that you want (quite obvious variable name)
const the2DArrayYouWant = elements.map(element => [
        element['userId'],
        convertAmount(element['amount'])
]);


console.log(the2DArrayYouWant);

在这里上面的代码中,这the2DArrayYouWant是一个数组数组,现在你可以迭代并且......也许做一个reduce或什么的。

最后console.log应该向您展示如下内容:

[
  [ 1, '$1,000.07' ],
  [ 42, '$1,135.25' ],
  [ 156, '$9,040.00' ],
  ...
]

注意:如果您坚持理解element => ([ ... ])代码片段,它们只是没有名称的函数。

// A function that will run some received function
function runThisFunction( receivedFunction ) {
  const numberTen = 10;

  return receivedFunction( numberTen );
}


// Writing this
function doubleValue(value) {
  return value * 2;
}

runThisFunction( doubleValue ); // 20


// Is the same thing as writing this
runThisFunction( (value) => { 
  return value * 2;
});


// That is the same thing as writing this
runThisFunction( value =>  value * 2 );

希望这会有所帮助,玩得开心!


推荐阅读