如何对对象数组进行字符串化处理? [英] How do I stringify an array of objects?

查看:98
本文介绍了如何对对象数组进行字符串化处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个对象数组,需要将其存储并保存到另一个页面.

I have created an array of objects that needs to be stored and kept for another page.

对象数组与此类似:

var cheese_array = [
  {
    name: "Chedder",
    age: "34",
    smelly: true
  },
  {
    name: "Brie",
    age: "4",
    smelly: false
  },
  {
    name: "Blue Stilton",
    age: "13",
    smelly: true
  }
 ];

但是当我JSON.stringify()它时,它不对对象进行字符串化,仅对数组进行字符串化.所以我最终得到了一个看起来像这样的数组:

But when I JSON.stringify() it, it doesn't stringify the objects, only the array. So I end up with and array that looks like this:

[object Object], [object Object], [object Object]

那么如何在这些数组中对这些对象进行字符串化.

So how do you stringify these objects in this array.

然后,将这个对象数组传递给类似于以下内容的点击函数:

This array of objects is then passed to an on click function similar to this:

$("#a-button").click(function() {
  var cheese_arr_stringify = JSON.stringify(cheese_array);
  sessionStorage.cheeseArray = cheese_arr_stringify;
  if(sessionStorage.cheeseArray) {
    window.location.href = "../";
  }
 });

非常多,它将cheese_arr_stringify设置为对象数组的字符串化版本.然后,它将这个字符串化的代码设置为会话密钥.然后,一旦设置好CheeseArray,它就会将其发送到一个目录.

So pretty much, its sets cheese_arr_stringify to a stringified version of the array of objects. Then it sets this stringified code to a session key. Following this, once it has been set cheeseArray it send it up one directory.


这是在加密后的会话密钥的图像.在这种情况下,foodItems与cheeseArray相同


EDIT 2: This is an image of the session key after being stringified. In this case, foodItems is the same as cheeseArray


@Rayon要求摆弄小提琴,以便他可以看一下,我整理了一下,而且效果很好.问题是-我现在觉得很愚蠢-以至于我在调用数组而不是我编写的字符串化变量.


EDIT 3: @Rayon asked for a fiddle so he could have a look, I made it up and it had worked. The problem was - I feel so stupid now - that I was calling the array instead of the stringified var I had made.

推荐答案

您的对象缺少逗号,如下所示:

Your object misses a comma as shown below:

name: "Blue Stilton",
    age: "13"//comma is missing here
    smelly: true

JSON.stringify可以正常工作,如下所示.

JSON.stringify works fine as shown below.

var cheese_array = [
  {
    name: "Chedder",
    age: "34",
    smelly: true
  },
  {
    name: "Brie",
    age: "4",
    smelly: false
  },
  {
    name: "Blue Stilton",
    age: "13",
    smelly: true
  }
 ];
console.log(JSON.stringify(cheese_array))

但是我不确定如何获取日志[对象对象],[对象对象],[对象对象] 我假设您正在控制台记录其他内容,请检查您的代码.

However I am not sure how you get a log [object Object], [object Object], [object Object] I am presuming you are console logging something else please check that in your code.

这篇关于如何对对象数组进行字符串化处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆