在javascript中对对象的嵌套数组进行排序 [英] Sort nested array of object in javascript

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

问题描述

let arr = [{
  name: 'Apple',
  trades: [{
    date: '2017.01.01',
    volume: 100
  }, {
    date: '1995.02.01',
    volume: 150
  }, {
    date: '2008.01.01',
    volume: 250
  }]
}]

您好,我用Google搜索了许多文档来对JavaScript中的嵌套对象进行排序,但是我找不到解决方法,我费了很多时间,想问一下如何对对象数组进行排序.

Hello, I googled many documents for sorting nested object in JavaScript, but I couldn't find the way of my case and I struggled so many hours so I want to ask to how can I sort above array of objects.

我期望的结果是像这样的trades.date排序对象的数组

What I expected result is sort array of object by trades.date like this

sortedArray = [{
  name: 'Apple',
  trades: [{
    date: '2017.01.01',
    volume: 100
  }, {
    date: '2008.01.01',
    volume: 250
  }, {
    date: '1995.02.01',
    volume: 150
  }]
}]

我该怎么做?

推荐答案

arr[0].trades.sort(function(a, b) {
    return (new Date(b.date) - new Date(a.date));
});

您可以使用数组的sort方法来实现此目的.如果要以相反的顺序排序,则只需在返回代码中交换a和b.

You can use the array's sort method for achieving this. If you want to sort in the reverse order then just swap a and b in the return code.

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

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