I cannot get the value of ‘Date’ key to build my array.
const input = [{ "Date": "12/08/2020", "Day": "Wednesday" }, { "Date": "13/08/2020", "Day": "Thursday" }, { "Date": "14/08/2020", "Day": "Friday" }]; function get(o, days) { const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const [dd, mm, yyyy] = Object.keys(o)[0].split('/'); const date = new Date(`${yyyy}-${mm}-${dd}`); date.setUTCDate(date.getUTCDate() + days); const key = `${ `${date.getUTCDate()}`.padStart(2, '0') }/${ `${(date.getUTCMonth() + 1)}`.padStart(2, '0') }/${ date.getUTCFullYear() }`; const value = weekdays[date.getUTCDay()]; return { [key]: value }; } function prepend(array, count) { while (count-- > 0) { array.unshift(get(input[0], -1)); } } function append(array, count) { while (count-- > 0) { array.push(get(input[input.length - 1], 1)); } } prepend(input, 1); append(input, 1); console.log(input);
The console shows this output:
{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}
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.
const [dd, mm, yyyy] = Object.values(o)[0].split('/');
However, since you already know the name of the key, you can simply use o.Date
.
const [dd, mm, yyyy] = o.Date.split('/');