I have two arrays in JavaScript:
a = [2, 5, 8, 10, 12, 15]
and
b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]
I want to turn this into an object of objects, like so:
ts = {
{
value: 2,
time: "2022-01-01"
},
{
value: 5,
time: "2022-01-02"
},
{
value: 8,
time: "2022-01-03"
},
{
value: 10,
time: "2022-01-04"
},
{
value: 12,
time: "2022-01-05"
},
{
value: 15,
time: "2022-01-06"
}
}
I have looked at the forEach method and the reduce method, e.g. from https://bobbyhadz.com/blog/javascript-create-object-from-two-arrays , but I am struggling. Edit: my attempt was along the lines of:
const ts = {};
a.forEach((a_value, index) => {
ts.value[index] = a_value[index];
});
A simple for loop will work if both lists are the same size.
let a = [2, 5, 8, 10, 12, 15]
let b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]
let ts = []
for (let idx in a) {
ts.push({value: a[idx],
time: b[idx]})
}
console.log(ts)