[英]Transform structure of array of objects
I have data like - 我有类似的数据-
var data = [{"DefaultZone":[{"key":"stream0","value":100},
{"key":"stream1","value":50},
{"key":"stream2","value":10}
]},
{"Zone 1":[{"key":"stream0","value":120},
{"key":"stream1","value":55},
{"key":"stream2","value":15}
]}
]
and wanted to transform it like - 并希望将其转换为-
var data = [{"key": "stream0", "values":[{"x":"DefaultZone","y":100}, {"x":"Zone 1","y":120}]},
{"key": "stream1", "values":[{"x":"DefaultZone","y":50}, {"x":"Zone 1","y":55}]},
{"key": "stream2", "values":[{"x":"DefaultZone","y":10}, {"x":"Zone 1","y":15}]}
];
using JavaScript(ES6). 使用JavaScript(ES6)。 Any help would be highly appreciated..
任何帮助将不胜感激。
Here is the first way that came to mind: 这是想到的第一种方法:
var data = [{ "DefaultZone": [ { "key": "stream0", "value": 100 }, { "key": "stream1", "value": 50 }, { "key": "stream2", "value": 10 }] }, { "Zone 1": [ { "key": "stream0", "value": 120 }, { "key": "stream1", "value": 55 }, { "key": "stream2", "value": 15 }] }]; let working = data.reduce((p, c) => { let x = Object.keys(c)[0]; c[x].forEach(v => { if (!p[v.key]) p[v.key] = []; p[v.key].push({ x: x, y: v.value }); }); return p; }, {}); let output = Object.keys(working).map(v => ({ key: v, values: working[v] })); console.log(output);
Further reading: 进一步阅读:
Although I like nnnnnn's answer, here is another one, using only the Object.keys() method: 尽管我喜欢nnnnnn的答案, 但这是另一个答案,仅使用Object.keys()方法:
var data = [{ "DefaultZone": [{ "key": "stream0", "value": 100 }, { "key": "stream1", "value": 50 }, { "key": "stream2", "value": 10 }] }, { "Zone 1": [{ "key": "stream0", "value": 120 }, { "key": "stream1", "value": 55 }, { "key": "stream2", "value": 15 }] }] final = {} data.forEach(function(x) { Object.keys(x).forEach(function(y) { x[y].forEach(function(z) { if (!final[z['key']]) final[z['key']] = []; final[z['key']].push({ 'x': y, 'y': z['value'] }) }) }) }) answer = [] Object.keys(final).forEach(function(x) { answer.push({ 'key': x, values: final[x] }) }) console.log(answer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.