将数组对象转换为对象数组

Convert object of arrays to array of objects

我有以下格式的源数据(数组对象):

{
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
}

并且我希望将数据转换为以下格式(对象数组):

[
    {
        value: 59,
        dayOfWeek: 'Thursday',
        dayOrNight: 'N'
    },
    {
        value: 58,
        dayOfWeek: 'Friday',
        dayOrNight: 'D'
    },
    {
        value: 62,
        dayOfWeek: 'Saturday',
        dayOrNight: 'N'
    },
    ...
]

这与 this question 有点相反。

执行此操作的适当命令组合是什么,是否使用例如lodash 还是其他?

结合map方法和按键访问对象,可以达到预期效果:

data.value.map((s, i) => ({value: s, 
   dayOfWeek: data.dayOfWeek[i], dayOrNight: data.dayOrNight[i]}));

一个例子:

let data = {
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
};

const result = data.value.map((s, i) => ({value: s, 
   dayOfWeek: data.dayOfWeek[i], dayOrNight: data.dayOrNight[i]}));
console.log(result);

更新:

您的方法略有修改:

let data = {
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
};

const result = Object.values(data)[0].map((s, i) => {
    let obj = {};
    for (let key in data) {
            obj[key] = data[key][i];
    }
    return obj;
});
console.log(result);