javascript - 对对象数组进行排序 - 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"}
]
推荐阅读
- sql - 使用 STRING_AGG 函数时子查询返回多行
- jupyter-notebook - Jupyter 笔记本服务器:限制对选定 IP 的访问
- python - 如何从 django 管理员下载最新上传的文件?
- python - 如何从 Python 中的 WTForm 字段中提取值?
- jenkins - 使用 Jenkins 签出项目时获取远程 repo 'origin' 时出错
- python - 如何在 tkinter 窗口中显示控制台窗口输出结果?
- spring - Spring Cloud Resilience4j Circuitbreaker 未调用回退
- python - 使用 Python 通过子文件夹中的消息保存 Outlook 中的附件
- reactjs - Ag 网格 excel 导出覆盖行号和列标签字体大小
- c++ - 在 OpenGL 窗口内绘制 gnuplot 图