0

How can I create a function to convert only these two fields "todaysDate & shippingDate" from string to Date type in place?

const jsonPayload = {
 todaysDate: "03/06/2021",
 shippingDate: "01/06/2021",
 color: "Blue",
 clothes: "T-shirt",
 price: 45
}

Andres
  • 731
  • 2
  • 10
  • 22

3 Answers3

1

This should do the trick,

const jsonPayload = {
  todaysDate: '03/06/2021',
  shippingDate: '01/06/2021',
  color: 'Blue',
  clothes: 'T-shirt',
  price: 45,
};

if (jsonPayload['todaysDate'] && typeof jsonPayload['todaysDate'] === 'string') {
  jsonPayload['todaysDate'] = new Date(jsonPayload['todaysDate']);
}

if (jsonPayload['shippingDate'] && typeof jsonPayload['shippingDate'] === 'string') {
  jsonPayload['shippingDate'] = new Date(jsonPayload['shippingDate']);
}

console.log(' ~ file: index.js ~ line 8 ~ jsonPayload', jsonPayload);

Here I first check if the key that we want exists, and then again check if the key's value is a string.
These checks help avoid cases where the key could be undefined or have a non-string value.
If both these checks pass I create a data object with the string value and assign it to the key in the object

Ramaraja
  • 2,526
  • 16
  • 21
1

Simple enough

const jsonPayload = {
    todaysDate: "03/06/2021",
    shippingDate: "01/06/2021",
    color: "Blue",
    clothes: "T-shirt",
    price: 45,
};


function foo(jsonPayload) {
    return {
        ...jsonPayload,
        todaysDate: new Date(jsonPayload.todaysDate),
        shippingDate: new Date(jsonPayload.shippingDate)
    }
}

foo(jsonPayload);
// {
//     todaysDate: 2021-03-05T23:00:00.000Z,
//     shippingDate: 2021-01-05T23:00:00.000Z,
//     color: "Blue",
//     clothes: "T-shirt",
//     price: 45
// }
Filip Seman
  • 1,252
  • 2
  • 15
  • 22
1

If in format mm/dd/yyyy:

const jsonPayload = {
  todaysDate: '03/06/2021',
  shippingDate: '01/06/2021',
  color: 'Blue',
  clothes: 'T-shirt',
  price: 45,
};

const convert_dates = (object, keys) =>
  keys.forEach((key) => object[key] = new Date(object[key]));

convert_dates(jsonPayload, ['todaysDate', 'shippingDate']);

console.log(jsonPayload);

If in format dd/mm/yyyy:

const jsonPayload = {
  todaysDate: '03/06/2021',
  shippingDate: '01/06/2021',
  color: 'Blue',
  clothes: 'T-shirt',
  price: 45,
};

const new_d_first_date = (string) => {
  const [d, m, y] = string.split('/');
  return new Date(Date.UTC(+y, +m - 1, +d));
};

const convert_dates = (object, keys) =>
  keys.forEach((key) => object[key] = new_d_first_date(object[key]));

convert_dates(jsonPayload, ['todaysDate', 'shippingDate']);

console.log(jsonPayload);
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8