开发者社区> 问答> 正文

将url后的参数键值对转换成JSON数组格式效率最高的方法是什么?


http: //www.a.com/admin/index.php#route=main/nav&user=tom&id=123/profile

后的参数转换成:

[
{"router":"main"},
{
"nav":"",
"user":"tom",
"id":"123"
},
{"profile":""}
]

除了循环变量有没有更简洁的方法

展开
收起
爵霸 2016-02-29 15:59:24 3574 0
1 条回答
写回答
取消 提交回答
  • 'use strict';
    
    var url = 'http: //www.a.com/index.php?route=main&nav&user=tom&id=123&profile';
    var querys = url
        .substring(url.indexOf('?') + 1)
        .split('&')
        .map((query) => query.split('='))
        .reduce((params, pairs) => (params[pairs[0]] = pairs[1] || '', params), {});
    
    console.log(querys);
    //{ route: 'main', nav: '', user: 'tom', id: '123', profile: '' }
    2019-07-17 18:50:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载