Store JS object array in a cookie, without plugins?

前端 未结 1 1304
说谎
说谎 2021-01-15 15:02

What\'s the best way to store this:

var mydata = [{\'11 Alveston Road, Manchester\':1},
              {\'12 Plymouth Street, Liverpool\':2}];
相关标签:
1条回答
  • 2021-01-15 15:52

    This sounds like a job for JSON.stringify:

    var myData = JSON.stringify(
        [
            {'11 Alveston Road, Manchester':1},
            {'12 Plymouth Street, Liverpool':2}
        ]
    ); // "[{"11 Alveston Road, Manchester":1},{"12 Plymouth Street, Liverpool":2}]"
    

    The array is converted into a string in JSON format, which you can then use as the value of your cookie. You can decode it with JSON.parse.


    Note: since you are using mobile browsers, they're probably quite modern and so have JSON natively installed. You can use this library to work around this in these cases.

    0 讨论(0)
提交回复
热议问题