如何在循环中将 JSON 元素分配给二维数组 [英] How to assign JSON elements to a 2D array while in a Loop

查看:62
本文介绍了如何在循环中将 JSON 元素分配给二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

JSON{页面":1",每页":10,总":100,总页数":10,数据":[{id":1,用户 ID":1,"userName":"Jim Silver",时间戳":16425382171,"txnType":"借方","amount":"$1,000.07",位置":{id":2,"address":"654,某处,某条街","city":"某城市","邮政编码":12345},"ip":"202.210.105.105"},{"id":2," ...}

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

[1, 1000]//用户 ID = 1,对应金额 = 1000[2, 2000]//用户 ID = 2, ...[3, 3000][4, 4000]...

我用三个类为我的 JSON 建模,描述了 JSON 对象中的三个级别.

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

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

for (int datum = 0; datum 

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

解决方案

我觉得这方面缺乏相关信息,所以我会在这里或那里推断一些东西.

我假设:

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

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

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

//在这里想象你的闪亮美丽的 JSONconst jsonData = require('./data.json');//这是您的JSON page 1"数据字段(事物数组)const 元素 = jsonData.data;//编写您的助手以将金额"字符串转换为您需要的内容函数 convertAmount(rawAmount) {//你的金额解析器应该在这里(货币字符串 -> 你想要的整数)//我只是直接返回,你可以改用返回原始金额;}//这个....就是你想要的二维数组(很明显的变量名)const the2DArrayYouWant = elements.map(element => [元素['userId'],转换金额(元素['金额'])]);console.log(the2DArrayYouWant);

在上面的代码中,the2DArrayYouWant 是一个数组数组,现在你可以迭代......也许做一个 reduce 之类的.

最后的 console.log 应该显示如下内容:

<预><代码>[[ 1, '$1,000.07' ],[ 42, '$1,135.25' ],[156,'$9,040.00'],...]

<小时>

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

//一个将运行一些接收到的函数的函数函数 runThisFunction( receivedFunction ) {const numberTen = 10;返回 receivedFunction( numberTen );}//写这个函数双值(值){返回值 * 2;}runThisFunction( doubleValue );//20//和写这个一样runThisFunction( (值) => {返回值 * 2;});//这和写这个是一样的runThisFunction( value => value * 2 );

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

I'm trying to assign two items (user ID, amount) at the same level in a JSON object into a 2D array for each user ID in the JSON object (assume this object has 10 user IDs so 2D array should have 10 rows with User ID as column 0 and Amount as column 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," ...}

The result should be (amount converted to integer and Math.Floor applied):

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

I modeled my JSON with three classes depicting the three levels in the JSON object.

I've declared a 2D array: int[,] userTxnsArr = new int[1, model.data.Count]; (10 rows, 2 columns)

Now loop through the deserialized JSON object in model:

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

But I'm only getting the last JSON record in the 2D array (so only one row of data). How do I assign each JSON record into each row of the 2D array? Thanks in advance.

解决方案

I'm feeling lacking infos about this, so I'll infer something here or there.

I'm assuming that:

  • You have all information in your "page": "1"
  • The language you're using can be javascript
  • If this is not the language you want, the algorithm will be very similar due to language nature

I took the liberty of create some variables to easify some things, then... when I say jsonData, well... its your JSON data, no miracles here.

I'd tested it using nodejs just to do not see the JSON, but it'll work in modern browsers as well (assigning directly the JSON data)

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

In the code above here, the the2DArrayYouWant is an Array of Arrays, now you can iterate and... maybe do a reduce or something.

The console.log at the end should show you something like this:

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


Note: If you're stucking to understand the element => ([ ... ]) code pieces, they are just functions without names.

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

Hope this helps, have fun!

这篇关于如何在循环中将 JSON 元素分配给二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆