变换对象数组的结构

时间:2016-09-05 02:27:25

标签: javascript ecmascript-6

我有像 -

这样的数据
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}
                  ]}
       ]        

并希望将其转换为 -

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}]}
   ];

使用JavaScript(ES6)。任何帮助都将受到高度赞赏..

2 个答案:

答案 0 :(得分:4)

这是我想到的第一种方式:

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);

进一步阅读:

答案 1 :(得分:0)

虽然我喜欢nnnnnn's回答,但这是另一个,仅使用the Object.keys() method:



except (ValueError, TypeError):