如何转换一个JavaScript对象?

时间:2019-06-25 15:58:45

标签: javascript

有人可以建议一种节省内存的方式(javascript代码)来转换javascript对象吗

[
  {"id":"1234560abcdef","metricA":7,"date":"2015-04-09T14:30:00.000Z","metricB":12},
  {"id":"7890abcdef123","metricA":5,"date":"2015-04-09T22:30:00.000Z","metricB":3}
]

到另一个对象

[                //data point:  [value, milliseconds since 1/1/1970 UTC]
   { 
     "target":"metricA", 
     "datapoints":[ [7,1428589800000], [5,1428618600000] ]
   },
   { 
     "target":"metricB",
     "datapoints":[ [12,1428589800000], [3,1428618600000] ]
   }
]

具有未知数量的数据点(从零到几百个)?

对于感兴趣的任何人,前者是数据库查询的输出,而后者是预期的Grafana JSON data-source响应。

我使用以下代码,但想知道是否有更好/更有效的方法(例如,不需要构建输入对象的副本的方法)。

// use date.js for date parsing (https://github.com/datejs/Datejs)
<script type="text/javascript" src="date.js"></script>

<script>
// input object
var inp = 
[ 
  {"id":"1234560abcdef","metricA":7,"date":"2015-04-09T14:30:00.000Z","metricB":12},
  {"id":"7890abcdef123","metricA":5,"date":"2015-04-09T22:30:00.000Z","metricB":3}
]

// initialize output object
var out = [ { "target":"metricA","datapoints":[]},{ "target":"metricB","datapoints":[]}];


var d, t;
for (var i=0; i < inp.length; i++) {
  d = Date.parse(inp[i].date);
  console.log(inp[i]);
  t = [ inp[i].metricA, d]; out[0].datapoints.push(t);
  t = [ inp[i].metricB, d]; out[1].datapoints.push(t);
}

console.log(JSON.stringify(out));

</script>

0 个答案:

没有答案