Javascript 对对象数组进行排序-节点
我试图根据javascript中的num对以下数组进行排序Javascript 对对象数组进行排序-节点,javascript,sorting,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"}',
[ { 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"}
]
你好到目前为止,您尝试了什么?排序回调应该返回一个数字,而不是布尔值。JSON.parsea.info.num-JSON.parseb.info.num-我不想知道我犯了多少次这样的错误。。。谢谢菲利克斯·克林,太好了!!我不认为我应该同时使用array.sort和json.parse。