In JavaScript, you can have objects, like this:
var a = { foo: 12, bar: 34 };
Or arrays with key (named) indexes, like this:
var b = [];
b['foo'] = 56;
b['bar'] = 78;
They're somewhat similar, but obviously not the same.
Now the strange thing is, JSON.stringify doesn't seem to take the array. No errors or anything, JSON.stringify(b) just results in [].
See this jsfiddle example. Am I doing something wrong, or do I just misunderstand how arrays work?
Stringify a JavaScript Array. Use the JavaScript function JSON.stringify () to convert it into a string. The result will be a string following the JSON notation. You will learn how to send JSON to the server in the next chapter.
The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON.stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.
Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation. myJSON is now a string, and ready to be sent ...
Arrays as JSON Objects. Example. [ "Ford", "BMW", "Fiat" ] Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
Javascript doesn't support Associative arrays (Like PHP).
var b = [];
Declaring explicitly an array, when you are trying to create an Object.
Arrays in Javascript can only contain the Index approach of Arrays, while Objects are more of Associative arrays.
If you change var b = [];
to var b = {};
it will solve the problem.
var b = {}
Declaring explicitly an Object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With