javascript 数组数组,JSON.stringify() 给出空数组而不是整个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28500851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:05:01  来源:igfitidea点击:

Array of Array, JSON.stringify() giving empty array instead of entire object

javascriptarraysjsonobject

提问by Eat Salad

Here's my array (from Chrome console):

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

array in Chrome console

Chrome 控制台中的数组

Here's the pertinent part of code:

这是代码的相关部分:

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

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

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

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

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

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

I tried some other stuff like Convert array to JSONor Convert javascript object or array to json for ajax databut the problem remains.

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

回答by Jamiec

Here is the minimal amount of javascript to reproduce the issue

这是重现问题的最少量 javascript

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

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.

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

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

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

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

回答by The Spooniest

Like all JavaScript objects, Arrays can have propertieswith string-based keys like the ones you're using. But only integer keys (or keys that can be cleanly converted to integers) are actually treated as elementsof an Array. This is why JSON isn't catching your properties, and it's also why your Arrays are all reporting their length as zero.

与所有 JavaScript 对象一样,数组可以具有基于字符串的键的属性,例如您正在使用的键。但是只有整数键(或可以干净地转换为整数的键)实际上被视为Array 的元素。这就是 JSON 没有捕获您的属性的原因,也是您的数组都将其长度报告为零的原因。

If you really need to use non-integer keys, you should be using plain Objects, not Arrays. This method has its own gotchas -for example, you need to be careful with for-in loops- but JSON will work the way you expect it to.

如果你真的需要使用非整数键,你应该使用普通的 Objects 而不是 Arrays。这个方法有它自己的问题——例如,你需要小心 for-in 循环——但是 JSON 会按照你期望的方式工作。

var hours = {
    "Mon" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
    "Tue" : {},
    "Wed" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
    "Thu" : {},
    "Fri" : {},
    "Sat" : {},
    "Sun" : {
        "11h30" : "15h00",
        "18h30" : "21h30"
    }, 
}

回答by DeveloperWithACaffeineProblem

In javascript arrays have indexes that are numeric keys. JSON.stringify assumes that an array have only properties which are numbers.

在 javascript 数组中,索引是数字键。JSON.stringify 假设数组只有数字属性。

You want to use an object, as what you have is not an array, but resembles a dictionary.

您想使用一个对象,因为您拥有的不是数组,而是类似于字典。

Here is an example I made: http://jsfiddle.net/developerwithacaffeineproblem/pmxt8bwf/2/

这是我做的一个例子:http: //jsfiddle.net/developerwithacaffeineproblem/pmxt8bwf/2/

object = Object()
object["age"] = 1
object["cars"] = 2
object["girlfriends"] = 3

JSON.stringify(object)

Results in:
"{"age":1,"cars":2,"girlfriends":3}"

结果:
“{“年龄”:1,“汽车”:2,“女朋友”:3}“

Afterwards when you parse the data if you want to iterate it you can use a piece of code similiar to this:

之后,当你解析数据时,如果你想迭代它,你可以使用一段与此类似的代码:

for (var key in yourobject) {
  if (yourobject.hasOwnProperty(key)) {
     console.log(key, yourobject[key]);
  }
}