【问题标题】:Parse JSON in TypeScript - add 'data' tag在 TypeScript 中解析 JSON - 添加“数据”标签
【发布时间】:2019-02-02 20:25:09
【问题描述】:

拥有如下所示的 JSON

[  
   {  
      "id":1,
      "position":3,
      "articleNumber":"ServiceElement"
   },
   {  
      "id":2,
      "position":2,
      "articleNumber":"ServiceElement"
   }
]

有没有可能通过任何的方式让它像:

{  
   "data":[  
      {  
         "data":{  
            "id":1,
            "position":3,
            "articleNumber":"ServiceElement"
         }
      },
      {  
         "data":{  
            "id":2,
            "position":2,
            "articleNumber":"ServiceElement"
         }
      }
   ]
}

我需要该 data 标记来识别不符合我给定 JSON 的 TreeTable 实现的对象。

【问题讨论】:

    标签: json angular typescript parsing treetable


    【解决方案1】:

    只需使用map 函数来改变物品的形状。

    对于第一级,我们创建一个新对象{ data: },然后将array.map 的结果分配给data 属性。

    const array = [  
       {  
          "id":1,
          "position":3,
          "articleNumber":"ServiceElement"
       },
       {  
          "id":2,
          "position":2,
          "articleNumber":"ServiceElement"
       }
    ];
    
    const mapped = { data: array.map(item => ({ data: item }))};
    console.log(mapped);

    【讨论】:

    • 直截了当的解决方案。也可以添加一些解释。
    • 它工作得几乎完美。问题是这会生成一个“数据”对象数组:[ {“data”:[ ...而不是包含数据对象数组的对象“数据”,就像我的例子中一样
    猜你喜欢
    • 2013-04-21
    • 2021-10-07
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多