简体   繁体   English

使用 angular 5 或 javascript 将 json 对象转换为特定格式的数组

[英]Convert json object into specific format array using angular 5 or javascript

I have a json data that looks like below.我有一个如下所示的 json 数据。

  [{
   {name: "box: 122",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-   12T00:10:00.379Z"], y=[0, 3, 5]},
   {name: "box: 125",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], y=[1,5,2]}
  }]

Now I want to format this json to below format.现在我想将此json格式化为以下格式。

output :输出 :

{ 
box: 122,  "2018-01-12T00:01:56.480Z",  0 
box: 122 ,"2018-01-12T00:05:58.116Z" ,  3
box: 122 ,"2018-01-12T00:10:00.379Z",   5
box: 125,  "2018-01-12T00:01:56.480Z",  1
box: 125, "2018-01-12T00:05:58.116Z",   5
box: 125,  "2018-01-12T00:10:00.379Z"   2
}

Basically I will have export this data to csv file.I have tried many code snippet but none of them fulfill desired result.基本上我会将这些数据导出到 csv 文件。我尝试了很多代码片段,但没有一个能达到预期的结果。 Can anyone help me how to do this in javascript.任何人都可以帮助我如何在 javascript 中做到这一点。 Thanks in advance.提前致谢。

Few observations :一些观察:

  • Your JSON is not a valid JSON .您的JSON不是有效的JSON
  • JSON does not support = . JSON 不支持= use : instead of = .使用:而不是=
  • valid JSON should be like Array of objects :有效的 JSON 应该类似于Array of objects

    在此处输入图片说明

Solution as per the requirement :根据要求解决方案:

 var jsonObj = [{ "name": "box: 122", "x": ["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], "y": [0, 3, 5] }, { "name": "box: 125", "x": ["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], "y": [1, 5, 2] }]; var tableString = "<table>", body = document.getElementsByTagName('body')[0], div = document.createElement('div'); tableString += "<tr><td>name</td><td>x</td><td>y</td><tr>"; for (var i in jsonObj) { tableString += "<tr>"; tableString += "<td>" + jsonObj[i].name + "</td>"; tableString += "<td>" + jsonObj[i].x + "</td>"; tableString += "<td>" + jsonObj[i].y + "</td>"; tableString += "</tr>"; } tableString += "</table>"; div.innerHTML = tableString; body.appendChild(div);
 table, td { border: 1px solid black; }

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

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