按属性值对JavaScript对象的数组进行排序 [英] Sort array of JavaScript objects by property value

查看:74
本文介绍了按属性值对JavaScript对象的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象数组。我的数组定义如下:

I have an array of JavaScript objects. My array is defined like this:

var myObjects = [
  { id: '1', username: 'bill.jones', active: true, createdon: '03/29/2014' },
  { id: '2', username: 'woohoo', active: true, createdon: '03/28/2014' },
  { id: '3', username: 'someuser', active: true, createdon: '03/30/2014' }
];

此数组实际上是动态填充的。不过,我需要按创建的值按升序对结果进行排序。为此,我正在尝试使用lodash。 createdon值表示日期。目前,我正在尝试以下方法:

This array is actually dynamically populated. Still, I need to sort the results by the createdon value in ascending order. To do that, I'm trying to use lodash. The createdon value represents a date. Currently, I'm trying the following:

//  ORDER BY createdOn
myObjects.sort(function (a, b) {
  var date1 = new Date(a['createdon']);
  var date2 = new Date(b['createdon']);
  return date1 < date2;
});

_.forEach(myObjects, function(result) {
  console.log(result);
});

不幸的是,运行此函数后,myObjects仍未排序。我做错了什么?

Unfortunately, myObjects is still not sorted after I run this function. What am I doing wrong?

谢谢!

推荐答案

我刚刚通过lodash doc,也许你可以尝试 sortBy

I just went through lodash doc, and perhaps you could try sortBy

试一试: http://jsfiddle.net/ 3Wza8 /

var myObjects = [
    { id: '1', username: 'bill.jones', active: true, createdon: new Date('03/29/2014') },
    { id: '2', username: 'woohoo', active: true, createdon: new Date('03/28/2014') },
    { id: '3', username: 'someuser', active: true, createdon: new Date('03/30/2014') }
];

myObjects = _.sortBy(myObjects, 'createdon');

_.forEach(myObjects, function (result) {
    console.log(result);
});

编辑:正如Cookie Monster指出的那样,重要的是你的创建了字段是日期,而不是字符串。

as Cookie Monster pointed out, it's important that your createdon field is a Date, and not a string.

这篇关于按属性值对JavaScript对象的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆