V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
hoythan
V2EX  ›  JavaScript

js 有什么原生的方法可以吧 object 转为 string key=value 形式吗?

  •  
  •   hoythan · 2017-12-26 21:49:30 +08:00 · 5038 次点击
    这是一个创建于 2306 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如对象 { test:1, test2:2 }

    转成字符串

    test=1&test2=2

    10 条回复    2018-01-11 10:38:23 +08:00
    SoloCompany
        1
    SoloCompany  
       2017-12-26 22:11:54 +08:00   ❤️ 2
    Object.entries(o).reduce((arr, [k, v]) => arr.concat(encodeURIComponent(k) + '=' + encodeURIComponent(v)), []).join('&')
    hoythan
        2
    hoythan  
    OP
       2017-12-26 22:13:57 +08:00
    我以为有原生的方法~,不过这条棒棒的!
    airyland
        3
    airyland  
       2017-12-26 22:38:37 +08:00   ❤️ 1
    在 Node.js 里自带 querystring 模块

    const querystring = require('querystring')
    querystring.stringify(obj)
    autoxbc
        4
    autoxbc  
       2017-12-26 23:02:57 +08:00   ❤️ 3
    hahasong
        5
    hahasong  
       2017-12-27 01:18:07 +08:00 via iPad   ❤️ 1
    jq 的表单序列化也可以
    Nioty
        6
    Nioty  
       2017-12-27 02:55:30 +08:00 via Android   ❤️ 1
    用 of 迭代后 join 一下就可以
    shyling
        7
    shyling  
       2017-12-27 12:43:22 +08:00   ❤️ 1
    Object.keys(a).reduce((a,b) => a+=`${b}=${a[b]}`, '')
    8qwe24657913
        8
    8qwe24657913  
       2018-01-09 23:54:49 +08:00   ❤️ 1
    pmispig
        9
    pmispig  
       2018-01-10 16:39:30 +08:00
    这个是 urlencode 啊,python 里面,js 不知道有没
    d41d8cd98f
        10
    d41d8cd98f  
       2018-01-11 10:38:23 +08:00
    new URLSearchParams({ test:1, test2:2 }).toString()

    只有较新的浏览器才支持: https://caniuse.com/#feat=urlsearchparams
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1014 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 18:49 · PVG 02:49 · LAX 11:49 · JFK 14:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.