qqruza
qqruza

Reputation: 1417

AngularJS and JSON returns undefined

Hi I have got a data in LocalStorage as JSON string:

[
     {"Date":"28/04/2016","Time":"08:00","Title":"Title 1"},
     {"Date":"28/04/2016","Time":"08:30","Title":"Title 2"}
]

And my module.factory looks like:

module.factory('$schedule', function() {
        var schedule = {};

        var result = JSON.parse(localStorage.getItem('myAgenda'));

        schedule.items = [{
                title: result.Title,
                date: result.Date,
                time: result.Time           
        }];
        return schedule;
    });

When I am trying to get data it returns undefined. When I try to get a specific object like:

console.log(result[0].Title);

It works fine and shows only the first element. I guess I missing each definition but don't know how to do it. Please help me to get all results in my schedule.items.

And I am passing the result as items into:

module.controller('ScheduleController', function($scope, $schedule) {    
  $scope.items = $schedule.items; 
});

Many thanks.

Upvotes: 1

Views: 558

Answers (3)

Chris
Chris

Reputation: 3338

You are trying to access fields in an array without mentioning wich array element you want to access. If you want to enumerate all agenda entries and add them to your array, it should look something like this:

module.factory('$schedule', function () {
    var schedule = [];

    var result = JSON.parse(localStorage.getItem('myAgenda'));

    result.forEach(function (date) {
        schedule.push({
            title: date.Title,
            date: date.Date,
            time: date.Time
        })
    })

    return schedule;
});

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You should use .map over array, also add missing } in your last element of array.

var schedule = [];
//assuming result returns an array.
schedule = result.map(function(value){
   return {
        title: value.Title,
        date: value.Date,
        time: value.Time
   };
})

Upvotes: 1

Christian
Christian

Reputation: 58

Not familiar with module.factory, but it looks like result is an array of objects and you're accessing it like a single object when creating schedule.items.

You might have to iterate over the array and create an item per object in result.

Upvotes: 0

Related Questions