[英]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.