I cannot get the value of ‘Date’ key to build my array.
JavaScript
x
47
47
1
const input = [{
2
"Date": "12/08/2020",
3
"Day": "Wednesday"
4
}, {
5
"Date": "13/08/2020",
6
"Day": "Thursday"
7
}, {
8
"Date": "14/08/2020",
9
"Day": "Friday"
10
}];
11
12
function get(o, days) {
13
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
14
const [dd, mm, yyyy] = Object.keys(o)[0].split('/');
15
const date = new Date(`${yyyy}-${mm}-${dd}`);
16
17
date.setUTCDate(date.getUTCDate() + days);
18
19
const key = `${
20
`${date.getUTCDate()}`.padStart(2, '0')
21
}/${
22
`${(date.getUTCMonth() + 1)}`.padStart(2, '0')
23
}/${
24
date.getUTCFullYear()
25
}`;
26
const value = weekdays[date.getUTCDay()];
27
28
return {
29
[key]: value
30
};
31
}
32
33
function prepend(array, count) {
34
while (count-- > 0) {
35
array.unshift(get(input[0], -1));
36
}
37
}
38
39
function append(array, count) {
40
while (count-- > 0) {
41
array.push(get(input[input.length - 1], 1));
42
}
43
}
44
45
prepend(input, 1);
46
append(input, 1);
47
console.log(input);
The console shows this output:
JavaScript
1
2
1
{NaN/NaN/NaN: undefined},{Date: "12/08/2020", Day: "Wednesday"},{Date: "13/08/2020", Day: "Thursday"},{Date: "14/08/2020", Day: "Friday"},{NaN/NaN/NaN: undefined}
2
Seems like the problem is with Object.keys(o)[0]
. How can I fix this?
Advertisement
Answer
You actually want the first value, not the first key.
JavaScript
1
2
1
const [dd, mm, yyyy] = Object.values(o)[0].split('/');
2
However, since you already know the name of the key, you can simply use o.Date
.
JavaScript
1
2
1
const [dd, mm, yyyy] = o.Date.split('/');
2