我正在尝试根据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' }]
我该如何实现
答案 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"}
]