簡體   English   中英

排序對象數組-Node.js

[英]Sorting an array of Objects - 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' }]

我該如何實現

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM