V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
hoythan

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

  •  
  •   hoythan · Dec 26, 2017 · 5586 views
    This topic created in 3054 days ago, the information mentioned may be changed or developed.

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

    转成字符串

    test=1&test2=2

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

    const querystring = require('querystring')
    querystring.stringify(obj)
    hahasong
        5
    hahasong  
       Dec 27, 2017 via iPad   ❤️ 1
    jq 的表单序列化也可以
    Nioty
        6
    Nioty  
       Dec 27, 2017 via Android   ❤️ 1
    用 of 迭代后 join 一下就可以
    shyling
        7
    shyling  
       Dec 27, 2017   ❤️ 1
    Object.keys(a).reduce((a,b) => a+=`${b}=${a[b]}`, '')
    pmispig
        9
    pmispig  
       Jan 10, 2018
    这个是 urlencode 啊,python 里面,js 不知道有没
    d41d8cd98f
        10
    d41d8cd98f  
       Jan 11, 2018
    new URLSearchParams({ test:1, test2:2 }).toString()

    只有较新的浏览器才支持: https://caniuse.com/#feat=urlsearchparams
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1374 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 23:54 · PVG 07:54 · LAX 16:54 · JFK 19:54
    ♥ Do have faith in what you're doing.