将对象数组转换为对象数组的不同结构

时间:2016-01-07 21:46:04

标签: javascript dataset

如何转换此数据集

file = 
[ 
{ 
DeviceName: 'DeviceName1',
counter1: '85%',
counter2: '87%',
counter3: '75%',
counter4: '63%' },
{ 
DeviceName: 'DeviceName2',
counter1: '85%',
counter2: '87%',
counter3: '75%',
counter4: '63%' 
} 
]

进入这个

data = [
      {
        key: "Device1",
        color: "#51A351",
        values:
          [      
            { x : "counter1", y : '85%' },
            { x : "counter2", y : '87%' },
            { x : "counter3", y : '75%' },
            { x : "counter4", y : '63%' }
          ]
      },
      {
        key: "Device2",
        color: "#BD362F",
        values:
          [      
            { x : "counter1", y : '85%' },
            { x : "counter2", y : '87%' },
            { x : "counter3", y : '75%' },
            { x : "counter4", y : '63%' }
          ]
      }
    ];

这是我的尝试

file.map(function(d,i){return {key:d.DeviceName,color:i}})

但这只能让我这么做:

[ { key: 'DeviceName1', color: 0 },
  { key: 'DeviceName2', color: 1 } ]

3 个答案:

答案 0 :(得分:0)

这是你想要的吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/path/to/your/script.js"></script>

答案 1 :(得分:0)

首先定义颜色来自哪里。然后你可以循环/减少对象的属性(使用Object.keys())来构造values数组:

var colors = ["#51A351", "#BD362F"];

var result = file.map(function(item, i) {
    var values = Object.keys(item).reduce(function(r, key) {
        return key == 'DeviceName' ? r : r.concat({ x: key, y: item[key] });
    }, []);
    return {
        values: values,
        key: item.DeviceName,
        color: colors[i]
    };
});
console.log(result);

答案 2 :(得分:0)

此解决方案使用正则表达式将counter1,...移动到数组的正确位置。

&#13;
&#13;
var file = [{ DeviceName: 'DeviceName1', counter2: '87%', counter1: '85%', counter3: '75%', counter4: '63%' }, { DeviceName: 'DeviceName2', counter1: '85%', counter2: '87%', counter3: '75%', counter4: '63%' }],
    data = file.map(function (a, i) {
        var o = {
            key: a.DeviceName.split('Name').join(''),
            color: ['#51A351', '#BD362F'][i],
            values: []
        };
        Object.keys(a).filter(function (b) {
            return /^counter\d+$/.test(b);
        }).forEach(function (c) {
            o.values[c.match(/\d+/) - 1] = { x: c, y: a[c] };
        })
        return o;
    });
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
&#13;
&#13;
&#13;