排序对象数组-Node.js

时间:2018-10-11 23:17:12

标签: javascript sorting

我正在尝试根据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' }]

我该如何实现

1 个答案:

答案 0 :(得分:1)

结合使用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"}
]