将names数组与对象es6中的values数组相结合

时间:2017-04-02 13:54:18

标签: javascript

我正在使用Influxdata API并且数据以这种格式返回:

{
  "columns": [
    "time", 
    "commit_time", 
    "expiration_time", 
    "kafka_consumer_group", 
    "kafka_offset_group", 
    "kafka_topic", 
    "kafka_topic_parition", 
    "message_metadata"
  ], 
  "name": "offsets", 
  "values": [
    [
      "2017-04-01T22:51:50.301Z", 
      "1491087110301", 
      "1491173510301", 
      "group-general-service-master", 
      0, 
      "replica-conversion-dev", 
      "6", 
      "NO_METADATA"
    ], 
    [
      "2017-04-01T22:51:50.301Z", 
      "1491087110301", 
      "1491173510301", 
      "group-message-service-master", 
      2, 
      "service-dev", 
      "4", 
      "NO_METADATA"
    ], 
    [
      "2017-04-01T22:51:50.303Z", 
      "1491087110303", 
      "1491173510303", 
      "group-general-service-mk-threadc", 
      7073, 
      "posted-dev", 
      "1", 
      "NO_METADATA"
    ]
  ]
}

列和值是分开的但是如何将列和值数组组合在一起,以便值具有名称:

{
    [
     {
      "time": "2017-04-01T22:51:50.301Z", 
      "commit_time": "1491087110301", 
      "expiration_time": "1491173510301", 
      "kafka_consumer_group": "group-general-service-master", 
      "kafka_offset_group": 0, 
      "kafka_topic": "replica-conversion-dev", 
      "kafka_topic_partition": "6", 
      "message_metadata": "NO_METADATA"
     }
    ]...     
}

2 个答案:

答案 0 :(得分:1)

您想要的结果不是有效的对象/数组表示法。

假设您想获得一个对象数组,可以尝试以下方法:

res.values.map(arr => ({
    time: arr[0],
    commit_time: arr[1],
    expiration: arr[2],
    // you get the idea...
}));

或使用数组解构:

res.values.map(arr => {
    var obj = {};
    [
        obj.time,
        obj.commit_time,
        obj.expiration,
        // you get the idea...
    ] = arr;
    return obj;
});

答案 1 :(得分:0)

假设您需要一个对象数组,您可以迭代values数组,并对keys数组进行迭代,并将对象分配给收集对象。然后返回一个包含对象的新数组。

var data = { columns: ["time", "commit_time", "expiration_time", "kafka_consumer_group", "kafka_offset_group", "kafka_topic", "kafka_topic_parition", "message_metadata"], name: "offsets", values: [["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-general-service-master", 0, "replica-conversion-dev", "6", "NO_METADATA"], ["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-message-service-master", 2, "service-dev", "4", "NO_METADATA"], ["2017-04-01T22:51:50.303Z", "1491087110303", "1491173510303", "group-general-service-mk-threadc", 7073, "posted-dev", "1", "NO_METADATA"]] },
    result = data.values.map(a => Object.assign({}, ...data.columns.map((k, i) => ({ [k]: a[i] }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }