sd_dewasurendra
sd_dewasurendra

Reputation: 393

How to Update an object in an array

This is my Array

$scope.tooltipsArray = [
              {
                  date: 2018-10-10T07:03:43.835Z,
                  text: 'name1'
              },

              {
                  date: 2018-09-29T18:30:00.000Z,
                  text: 'name2'
              }     
          ];

How can I update date to locale date format like this.

 $scope.tooltipsArray = [
              {
                  date: Wed Oct 10 2018 14:05:27 GMT+0530 (India Standard Time),
                  text: 'name1'
              },

              {
                  date: Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time),
                  text: 'name2'
              }     
          ];

I have used map() to do that. But it does not work

var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });

Can anyone tell me how to do this from map() in JavaScript?

Upvotes: 0

Views: 98

Answers (4)

Usira
Usira

Reputation: 148

What map function does is going through array element one by one and run the callback function, so what you have to do is update the whole object or update one entry

el.date = new Date(el.date).toLocaleDateString();

Upvotes: 0

Niladri
Niladri

Reputation: 5962

You can use the below code -

    $scope.tooltipsArray = [
                  {
                      date: "2018-10-10T07:03:43.835Z",
                      text: 'name1'
                  },

                  {
                      date: "2018-09-29T18:30:00.000Z",
                      text: 'name2'
                  }     
              ];

    var vector = $scope.tooltipsArray.map(function(el) {return { 'date':new Date(el.date).toString(),'text':el.text}});
    console.log(vector);

The output will be like below -

[
{date: "Wed Oct 10 2018 12:33:43 GMT+0530 (India Standard Time)", text: "name1"}
{date: "Sun Sep 30 2018 00:00:00 GMT+0530 (India Standard Time)", text: "name2"}
]

Upvotes: 1

Zahema
Zahema

Reputation: 1415

1- Remove .value why is there in the first place?

2- You need to change the date inside the object and then return el instead of date if you just want the date to be changed, likewise:

    var vector = $scope.tooltipsArray.map(function(el) {
     el.date = new Date(el.date).toLocaleDateString();
     return el;
    });

Upvotes: 0

Vic
Vic

Reputation: 723

Why is there a .value key after tooltipsArray?

You assigned the array to tooltipsArray, so unless there's a Proxy involved, expect to access the array through $scope.tooltipsArray.

To fix it, just remove .value.

var vector = $scope.tooltipsArray.map(function (el) { return new Date(el.date).toLocaleDateString(); });

Upvotes: 0

Related Questions