简体   繁体   English

如何使用 typescript 展平 json 阵列并将其转换为 object

[英]How to flatten json array using typescript and Convert it as object

I am trying to convert a json array as a flat json using typescript.我正在尝试使用 typescript 将 json 阵列转换为平面 json。 I have a json as below:我有一个 json 如下:

"Fields" : [
    {
    "FieldName" : "xyz";
    "FieldValue" : {
     "Contents": {
      " Company": "ABC"
    }
    }
    }
    ]

I have to convert as below:我必须转换如下:

"xyz" :  {
      "Contents": {
      " Company": "ABC"
     }
    }
Here Fields should be replaced with "xyz", FieldName and FieldValue should need to be removed. 

Help me to achieve this using typescript.帮助我使用 typescript 实现这一目标。

If you really only want to work with that first item in your array just rearrange the data with something the following.如果您真的只想使用数组中的第一项,只需使用以下内容重新排列数据。

 const json = JSON.stringify({ Fields: [ { FieldName: "xyz", FieldValue: { Contents: { " Company": "ABC" } } } ] }); const parsedJson = JSON.parse(json); const expectedOutput = { [parsedJson.Fields[0].FieldName]: parsedJson.Fields[0].FieldValue }; console.log(expectedOutput);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM