0

I have an array of objects with String values that I want to convert to Date, but I'm getting the following error:

Uncaught SyntaxError: Unexpected token :

How should I correctly do this conversion and return the same object structure?

array = [
    {
        end: "2017-05-18T09:00:00.000Z",
        start: "2017-05-18T06:00:00.000Z"
    },
    {
        end: "2017-05-19T07:00:00.000Z",
        start: "2017-05-19T06:00:00.000Z"
    },
    {
        end: "2017-05-20T08:00:00.000Z",
        start: "2017-05-20T07:00:00.000Z"
    }
]

result = array.map((element) => {
  {
    end: new Date(element.end),
    start: new Date(element.start),
  }
})
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

4 Answers4

2

You either do:

result = array.map(element => ({
 end: new Date(element.end),
start: new Date(element.start),
}));

OR:

result = array.map(element => {
  return {
    end: new Date(element.end),
    start: new Date(element.start),
  };
})

May have a look at ECMAScript6 arrow function that returns an object

Community
  • 1
  • 1
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

The error you're getting is because javascript here thinks { end: new Date(element.end), start: new Date(element.start), } is a code block. Change it to

result = array.map((element) => {
  return {
    end: new Date(element.end),
    start: new Date(element.start),
  }
})
console.log(result)

You're missing a return.

gaganshera
  • 2,629
  • 1
  • 14
  • 21
1

You could wrap an object in parenthesis ad return value.

let array = [{ end: "2017-05-18T09:00:00.000Z", start: "2017-05-18T06:00:00.000Z" }, { end: "2017-05-19T07:00:00.000Z", start: "2017-05-19T06:00:00.000Z" }, { end: "2017-05-20T08:00:00.000Z", start: "2017-05-20T07:00:00.000Z" }],
    result = array.map(element => ({
        end: new Date(element.end),
        start: new Date(element.start),
    }));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

To return object using the arrow function you need extra brackets, like below:

results = array.map(el => ({ end: new Date(el.end), start: new Date(el.start) }) )
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
achwilko
  • 774
  • 5
  • 7