Having trouble with array slicing functionality?

I received a json list and stored it in an array.

{"event_date": "2016-12-07 01:39:41","created_at": "15/11/2016 às 06:10"}

Within this list, there is an attribute called "_date": "2016-12-07 01:39:41". I am attempting to extract the year '2016' and the day '07' from this attribute.

$scope.getPostsDate = function() {
        PostsService.getPosts($scope.token).then(function(result) {
            var postsByDate = result.data;
            angular.forEach($scope.postsByDate, function(value, key) {
                var oldDate = value.event_date;
                value.newDate = oldDate.slice(0, 10);
                console.log('date' +value.newDate);
            })
        })
    }

Outcome: TypeError: Cannot read property 'slice' of null at posts.ctrl.js:67 Console output: date 2016-11-28 I am confused because I successfully implemented a similar method before:

$scope.getPosts = function() {
        PostsService.getPosts($scope.token).then(function(result) {
            $scope.posts = result.data;
            angular.forEach($scope.posts, function(value, key) {
                var str = value.created_at;
                value.data = str.slice(0, 10);
                value.hour = str.slice(11, 25);
            })
            console.log($scope.posts);
        })
    }

Thank you

Answer №1

When handling your data, you are storing it in a local variable and later trying to access it through a property on $scope. To correct this issue, modify the forEach loop to correctly access the array:

$scope.processPostsDate = function() {
    PostsService.fetchPosts($scope.token).then(function(response) {
        var postsByDate = response.data;
        //postsByDate is a local variable, so access it directly
        angular.forEach(postsByDate, function(post, index) {
            var oldDate = post.event_date;
            post.newDate = oldDate.slice(0, 10);
            console.log('Updated date: ' + post.newDate);
        });
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate a fade out transition into the current tab-pane?

I am currently implementing Bootstrap 5.3 with a basic pills and tab structure, and I am looking for a way to smoothly add a fadeOut effect to the active tab before the fadeIn of the selected tab. It appears that simply adding the "fade" class only introd ...

Update the webpage post a database entry without relying on the setTimeout() function in Javascript

Is there a method to automatically refresh the page after a new entry in the database without relying on Javascript's setTimeout or setInterval functions? Could an AJAX function or a MySQL function accomplish this task instead? Must we continuously ...

Is iterating over an array of objects the same as avoiding repetitive code?

Update: Incorporating JavaScript with the three.js library. To streamline our code and prevent repetition, we utilize loops. However, in this specific scenario, the for loop is not functioning as expected compared to six similar lines that should achieve ...

Using a for loop to call a Node.js request function

I have arrays consisting of 8 elements each var array_pullrequest_id=["335","328","326","323","322","314","295","291"]; var array_uniqueName=["<a href="/cdn-cgi/l/email ...

Error: Scheme is not a valid function call

Currently, I am attempting to implement user registration functionality in a Node.js application using MongoDB. However, I encountered this error: var UtenteSchema = Scheme({ TypeError: Scheme is not a function Below is my model utente.js: cons ...

The dimensions of the body are set to 100vh in height and width. However, the div inside this body has a width of either 100vh or 100%, but it is not

I am trying to create a div element that has a width equal to the viewport of the browser. However, I am encountering issues when applying the CSS property width:100vh to the body element. Here is my code snippet: body { font-family: Staatliches; fo ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

How to dynamically delete React Router Link components after they have been clicked on?

When using React Router, how do I remove the div that contains a Link component or the Link component itself when it is clicked on and the routing is complete? For instance, consider an app structured in the following way: ==Header== ==Link1 Link2== Onc ...

Place a <script> tag within the Vue template

I am currently developing an integration with a payment service. The payment service has provided me with a form that includes a script tag. I would like to insert this form, including the script tag, into my component template. However, Vue does not allo ...

Restrict date range in Bootstrap Datepicker based on database values

Is there a way to remove specific date ranges from the database? For instance, if I have date ranges from 15.01.2021 to 21.01.2021 and from 24.01.2021 to 03.02.2021, is it possible to prevent these dates from being selected in the datepicker? I would lik ...

What are the limitations of using dynamic arrays as parameters in functions that utilize static array parameters?

Currently, I am delving into the world of C language and data structures. An intriguing question that has popped up in my mind is why we are unable to utilize dynamic arrays as parameters for functions that are designed to work with static array paramete ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

What is the best javascript framework to pair with twitter bootstrap?

After dabbling in twitter bootstrap, I discovered its impressive array of UI components. Interested in incorporating it into a project, my quest for a compatible javascript framework has left me torn between angularjs, backbonejs, and emberjs. Although I ...

Guide to transitioning an array to a different view controller in Swift?

I'm facing an issue where I attempt to transfer an array that is populated with Strings from the FactsViewController to the FavoritesViewController. However, after adding some elements to the array and running the code, when transitioning to the Favor ...

"Encountering an error with an Ajax request while trying to call an ActionResult in

Utilizing Angularjs alongside asp.net MVC, I am attempting to save data via an Ajax request, however, I am encountering an error message. The browser is displaying "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" ...

What is the best way to attach several URLs to a single component?

I am currently using Next.js Here is the structure I have: https://i.stack.imgur.com/jRQBS.png I am in need of opening the same component for multiple URLs, such as 'http://localhost:3000/hakkimizda', 'http://localhost:3000/cerez-politika ...

The ngOnChanges lifecycle hook is not being triggered

I've been working on a small project that involves two components: menu and bill. I'm trying to figure out how to make it so that when the quantity of any menu item is changed, the onChanges function in the bill component is called. I also need t ...

Retrieving precise information from the backend database by simply clicking a button

As a new full stack programmer, I find myself in a challenging situation. The root of my problem lies in the backend table where data is stored and retrieved in JSON format as an array of objects. My task is to display specific data on my HTML page when a ...

Unable to access the HTTP POST response data beyond the .subscribe method

I am facing an issue with accessing data from a variable set after making an HTTP request to a server. The request returns the correct data as a response, but I am unable to access the variable data from another method. Below is my code snippet: public u ...