我有一系列对象:

 var arr = [
    {
        timemark: "2017-03-01",
        db_total: c1,
        db_used: d1,
        hosts: e1,
        items: f1
    },{
        timemark: "2017-03-02",
        db_total: c2,
        db_used: d2,
        hosts: e2,
        items: f2
    },{
        timemark: "2017-03-03",
        db_total: c3,
        db_used: d3,
        hosts: e3,
        items: f3
    },..]


我正在努力如何将其转换为另一个具有不同结构的数组:

var result = [
    {
        topic: "db_total",
        data: [
            {
                x: "2017-03-01",
                y: c1
            },{
                x: "2017-03-02",
                y: c2
            },{
                x: "2017-03-03",
                y: c3
            },...]
    },{
        topic: "db_used",
        data: [
            {
                x: "2017-03-01",
                y: d1
            },{
                x: "2017-03-02",
                y: d2
            },{
                x: "2017-03-03",
                y: d3
            },...]
    },{
        topic: "hosts",
        data: [
            {
                x: "2017-03-01",
                y: e1
            },{
                x: "2017-03-02",
                y: e2
            },{
                x: "2017-03-03",
                y: e3
            },...]
    },{
        topic: "items",
        data: [
            {
                x: "2017-03-01",
                y: f1
            },{
                x: "2017-03-02",
                y: f2
            },{
                x: "2017-03-03",
                y: f3
            },...]
    },...];


我知道我必须做这样的事情:

//convert
var result = [];
for (var i=0; i<arr.length; i++) {
  result[i]=[arr[i].timemark];
}


创建数组数组:

[
    [2017-03-01],
    [2017-03-02],
    [2017-03-03]
]


几个小时后,这是一个开始。但是我找不到一种方法如何开始在数组而不是数组内部创建对象?试图走宝贝的步骤:)

但我确实在理解代码段时遇到问题,并且可能使用错误的语法无法正常工作。

有人可以解释在这种情况下如何正确使用循环吗?

最佳答案

您可以执行这样的逻辑;映射每个分组,并编译最终结果对象;



var arr = [
    {
        timemark: "2017-03-01",
        db_total: "c1",
        db_used: "d1",
        hosts: "e1",
        items: "f1"
    },{
        timemark: "2017-03-02",
        db_total: "c2",
        db_used: "d2",
        hosts: "e2",
        items: "f2"
    },{
        timemark: "2017-03-03",
        db_total: "c3",
        db_used: "d3",
        hosts: "e3",
        items: "f3"
    }];

var result = [];
Object.keys(arr[0])
      .filter(field => field != "timemark")
      .forEach(field => result.push(finalObj(field, arr.map(e => xy(e.timemark, e[field])))));

console.log(result);

function xy(x, y) {
     return { x : x, y : y };
}

function finalObj(name, arr) {
     return { topic : name, data : arr };
}





由于您建议您在最终对象中有更多字段,因此会有更多topic,如果是这种情况,我已经进行了修改,以便您添加的字段更多,它将自动显示在最终结果对象中。 (c的timemark字段除外)

关于javascript - 对象数组到包含数组的对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42589952/

10-11 06:47
查看更多