从一个具有不同值数组的单个键数组转换键值对

时间:2019-04-14 20:22:43

标签: javascript arrays

我需要转换json的键值对以在ejs表迭代中使用。

我将键值对转换为每个键-将值作为不可迭代的对象。

这里data.metaData是键,而data.rows是要映射的值。

var data = {
    metaData: [{
            name: "SCHEDULED_TIME"
        },
        {
            name: "TRIGGER_TIME"
        },
        {
            name: "START_TIME"
        },
        {
            name: "END_TIME"
        },
        {
            name: "CEC_ID"
        },
        {
            name: "TRIGGER_TYPE"
        },
        {
            name: "STATUS"
        },
        {
            name: "JOB_NAME"
        },
    ],
    rows: [
        [
            "12:20",
            null,
            null,
            null,
            null,
            null,
            null,
            "CLARITY_ETL",
        ],
        [
            "15:50",
            null,
            null,
            null,
            null,
            null,
            null,
            "CLARITY_ETL",
        ],
        [
            "18:30",
            null,
            null,
            null,
            null,
            null,
            null,
            "BUDGET_ETL",
        ],
    ]
}


**
Expected result as: **

data = [{
    "SCHEDULED_TIME": "12:20",
    "TRIGGER_TIME": null,
    "START_TIME": null,
    "END_TIME": null,
    "CEC_ID": null,
    "TRIGGER_TYPE": null,
    "STATUS": null,
    "JOB_NAME": "CLARITY_ETL",
}, {
    "SCHEDULED_TIME": "15:50",
    "TRIGGER_TIME": null,
    "START_TIME": null,
    "END_TIME": null,
    "CEC_ID": null,
    "TRIGGER_TYPE": null,
    "STATUS": null,
    "JOB_NAME": "CLARITY_ETL",
}, {
    "SCHEDULED_TIME": "18:30",
    "TRIGGER_TIME": null,
    "START_TIME": null,
    "END_TIME": null,
    "CEC_ID": null,
    "TRIGGER_TYPE": null,
    "STATUS": null,
    "JOB_NAME": "BUDGET_ETL",
}]

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是在rows上使用Array.map(),将每个row映射到object,即生成的{{1 }}来自keys

object
metaData

或者,如果您也使用Array.reduce(),则为简化版本。

var data = {
  metaData: [
    {name: "SCHEDULED_TIME"},
    {name: "TRIGGER_TIME"},
    {name: "START_TIME"},
    {name: "END_TIME"},
    {name: "CEC_ID"},
    {name: "TRIGGER_TYPE"},
    {name: "STATUS"},
    {name: "JOB_NAME"}
  ],
  rows: [
    ["12:20", null, null, null, null, null, null, "CLARITY_ETL"],
    ["15:50", null, null, null, null, null, null, "CLARITY_ETL"],
    ["18:30", null, null, null, null, null, null, "BUDGET_ETL"]
  ]
};

let res = data.rows.map((row) =>
{
    let obj = {};
    row.forEach((val, idx) => obj[data.metaData[idx].name] = val);
    return obj;
});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}