首页 > 解决方案 > 对对象数组进行排序 - Nodejs

问题描述

我正在尝试根据 javascript 中的 num 对以下数组进行排序

[ { name: 'sample',
    info: '{"num":10,"type":"detox"}',
    hex: 'bdafa7' },
  { name: 'sample',
    info: '{"num":5,"type":"detox"}',
    hex: 'bdafaj' },
  { name: 'sample',
    info: '{"num":0,"type":"detox"}',
    hex: 'bdafah' },
  { name: 'sample',
    info: '{"num":1,"type":"detox"}',
    hex: 'bdafay' }]

我怎样才能做到这一点

标签: javascriptsorting

解决方案


使用 Array.sort 和 JSON.parse 的组合:

let v = [ { name: 'sample',
    info: '{"num":10,"type":"detox"}',
    hex: 'bdafa7' },
  { name: 'sample',
    info: '{"num":5,"type":"detox"}',
    hex: 'bdafaj' },
  { name: 'sample',
    info: '{"num":0,"type":"detox"}',
    hex: 'bdafah' },
  { name: 'sample',
    info: '{"num":1,"type":"detox"}',
    hex: 'bdafay' }];

v.sort((a, b) => {
  return JSON.parse(a.info).num - JSON.parse(b.info).num
});

退货

[
  {name: "sample", info: "{"num":10,"type":"detox"}", hex: "bdafa7"},
  {name: "sample", info: "{"num":5,"type":"detox"}", hex: "bdafaj"},
  {name: "sample", info: "{"num":1,"type":"detox"}", hex: "bdafay"},
  {name: "sample", info: "{"num":0,"type":"detox"}", hex: "bdafah"}
]

推荐阅读