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

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

问题描述

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

Here's my array (from Chrome console):

以下是代码的相关部分:

Here's the pertinent part of code:

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

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

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"}

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

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