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