简体   繁体   中英

Return modified object with Underscore/Angular

With underscore, how can I format a particular value and return a new object?

For example I have the following structure:

var myData = [
  {
    'created': '2015-05-19T21:45:23',
    'sales': 200,
  },
  {
    'created': '2015-05-20T21:45:33',
    'sales': 100,
  },
  {
    'created': '2015-05-21T21:45:43',
    'sales': 140,
  },
  {
    'created': '2015-05-23T21:45:43',
    'sales': 200,
  }
];

I'd like to format the created key/value using angular's date filter function. How can I return a new object with the proper formatting?

When I do something using _.each , it doesn't work.

_.each(myData, function(k) {
  return $filter('date')(k.created, 'short');
})

What I want to output is:

var myModifiedData = [
  {
    'created': '5/19/15 9:45 PM',
    'sales': 200,
  },
  {
    'created': '5/20/15 9:45 PM',
    'sales': 100,
  },
  {
    'created': '5/21/15 9:45 PM',
    'sales': 140,
  },
  {
    'created': '5/22/15 9:45 PM',
    'sales': 200,
  }
];

each will only iterate over array but if you want to return new array you can use map (new in ES5):

$scope.newData = myData.map(function(item) {
    return $filter('date')(item.created, 'short');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM