【问题标题】:Need to convert two dimensional array response in to json Object in Angular 9需要将二维数组响应转换为Angular 9中的json对象
【发布时间】:2020-07-07 20:04:12
【问题描述】:

我收到来自后端(NodeJS)的响应,

当前回应

 [ [ '49' ], [ '33' ], [ '60' ], [ '58' ] ]

需要将上述这些值以 JSON 对象格式传递给 Highchart 组件,如下所示在我的前端 -Angular 9 中。我在将二维数组值转换为其相应的 json 格式时遇到问题。

这里的键'fin'和它的值应该是静态的。对于键 -“A”,我需要数组元素 1,3,.. 而对于键 -“B”,我需要数组元素 2,4 等。

谁能指导我,拜托。

要求的格式:

{
"fin":[
       '14',
       '16'
      ]
"A" : [
       '49',
       '60'
      ]
"B" : [
       '33',
       '58'
      ]
}

【问题讨论】:

  • 如果数组中的 (0) 位置有多个元素,例如 [['49, '2nd_ele'], [],...],输出是否应显示“A”: ['49', '2nd_ele', '60'] ?
  • 请发布您尝试过的内容和一些代码 sn-p。 SO 不编程服务。
  • @钱德拉。我只会在内部数组中得到一个数组元素(位置 0)..

标签: javascript angular


【解决方案1】:

一种解决方法是根据需要隔离 currentResponse 数组。

listA = [];
listB = [];
for (i = 0; i < currentResponse.length; i++) {
  if(i%2==0) listA.push(currentResponse[i][0]);
  else listB.push(currentResponse[i][0]);
}

一旦分离,我们可以将 JSON 构建为一个简单的 JS 对象

jsonObj = {
  fin : [
       '14',
       '16'
      ]
  A : listA
  B : listB
}

【讨论】:

  • 嗨 Chandra.. 感谢您的回答.. 成功了!..
猜你喜欢
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 2020-11-10
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多