我尝试了很多算法将内部有对象的数组转换为数组的数组。但每次要么它不起作用,要么我的新创建数组为空。例如,我无法使用 angular.foreach()
遇到它。或myArray.forEach(function(element))
。我真的不知道为什么,因为它被声明并初始化为 array "var myArray = [];"
。
然后我使用 push
填充它,我在 console.log 中获得的是:
我想要的是 _.SortBy(myArray, 'date');
中可用的东西(Underscore.js)要做到这一点我需要 myArray
像那样:
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
关注此帖子:Converting a JS object to an array我几乎尝试了列出的所有内容,但没有任何效果...你能帮我一下吗?
$scope.myArray = [];
// This is into an angular.foreach
$scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });
console.log("MyArray :", $scope.myArray);
编辑:
我的数组似乎有问题,我尝试了这两个函数,但我看不到任何 console.log()
……难道我的阵法被锁定了?也许没有函数(sort、_.sortBy...)可以遇到它?
// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
var date1 = new Date(x.date);
var date2 = new Date(y.date);
console.log("My dates :", date1);
console.log("My dates :", date2);
return date1 - date2 ;
});
// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}
// Even is showing the complete Array in console.log is working, this below shows me "undefined"
console.log("One element : "+$scope.newCal[1]);
最佳答案
就像其他人指出的那样,您应该能够做到 _.sortBy(myArray, 'date')
按日期对数组进行排序。
如果一切都失败了,你可以随时尝试 myArray.sort((a, b) => a.date < b.date)
关于javascript - 如何将 _.SortBy() 与对象数组一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944359/