1

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?

5
  • There's no JSON in this question, just arrays and objects. Might help with your searching if you leave off "json" from your search terms. Commented Aug 12, 2020 at 20:28
  • I guess you want o[Object.keys(o)[0]] instead of Object.keys(o)[0] or simply o.Date since you know the key already. Commented Aug 12, 2020 at 20:28
  • I want to use o.Date and tried but it didn't bring any results. Would you be able to amend my code please? Commented Aug 12, 2020 at 20:29
  • 1
    If you replace Object.keys(o)[0] in the code above with o.Date, the code works as I would expect it. Commented Aug 12, 2020 at 20:32
  • Thanks so much. It was the most helpful advice! Top answer! Commented Aug 12, 2020 at 20:34

1 Answer 1

1

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('/');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you and to @Heretic-Monkey. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.