数组数组,JSON.stringify() 给出空数组而不是整个对象 [英] Array of Array, JSON.stringify() giving empty array instead of entire object

查看:32
本文介绍了数组数组,JSON.stringify() 给出空数组而不是整个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数组(来自 Chrome 控制台):

Here's my array (from Chrome console):

这是代码的相关部分:

console.log(hours);
var data = JSON.stringify(hours);
console.log(data);

在 Chrome 的控制台中,我从最后一行得到 [].我应该得到 {'Mon':{...}...}

In Chrome's console I get [] from the last line. I should get {'Mon':{...}...}

以下是重现问题的最少 JavaScript:

Here is the minimal amount of JavaScript to reproduce the issue:

var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);    
console.log(JSON.stringify(test)); // outputs []

我尝试了一些其他的东西,比如将数组转换为 JSON将 javascript 对象或数组转换为 json 以获得 ajax 数据 但问题仍然存在.

I tried some other stuff like Convert array to JSON or Convert javascript object or array to json for ajax data but the problem remains.

推荐答案

这里是重现问题的最少 javascript

Here is the minimal amount of javascript to reproduce the issue

var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);    
console.log(JSON.stringify(test)); // outputs []

上述问题在于,虽然 javascript 很乐意让您将新属性后期绑定到 Array,但 JSON.stringify() 只会尝试序列化数组中的实际元素.

The issue with the above is that, while javascript will be happy to let you late-bind new properties onto Array, JSON.stringify() will only attempt to serialize the actual elements in the array.

使对象成为实际对象的最小更改,并且 JSON.stringify 按预期工作:

A minimal change to make the object an actual object, and JSON.stringify works as expected:

var test = {}; // here is thre only change. new array ([]) becomes new object ({})
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs {"11h30":"15h00","18h30":"21h30"}

这篇关于数组数组,JSON.stringify() 给出空数组而不是整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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