-2

I want day,month and year values from the value in an object.

{myDate : '12/31/2020'}

I want to do something like this:

d,m,y = mydate('/')

so that d= 12, m=31 , y = 2020 and they are separated using the '/' character

Is there a way to do something like this in JS?

Swayam Shah
  • 200
  • 1
  • 12
  • 1
    `let [d, m, y] = '12/31/2020'.split('/')` good enough for you ? – svarog Sep 26 '21 at 16:49
  • A simple [Google search](//google.com/search?q=site%3Astackoverflow.com+js+split+string+and+destructure) finds many results. MDN has documentation on [destructuring syntax](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and [String methods](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods). Please see [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/q/261592/4642212). – Sebastian Simon Sep 26 '21 at 16:55

3 Answers3

4

Split the string and destructure the resulting array:

const myDate = {myDate : '12/31/2020'}
const [d,m,y] = myDate.myDate.split('/')
console.log(d,m,y)
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
0

const [d,m,y] = '12/31/2020'.split("/")

console.log(d,m,y)
Alan Omar
  • 4,023
  • 1
  • 9
  • 20
0

Use

mydate = "12/30/2021";
var arr = mydate.split("/");
//arr[0]=12
//arr[1] is day
Subhashis Pandey
  • 1,473
  • 1
  • 13
  • 16
  • I guess the above posted answers were sufficient. As the user mentioned in the question that he/she wants to `destructure` the elements and not `access` them – Kartikey Sep 26 '21 at 17:57