Reputation: 495
I was trying to stringify a array of objects with extra properties.
var data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}];
data.extra = ["a", "b"];
console.log(data)
// [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}, extra: ["a", "b"]]
console.log(JSON.stringify(data));
//[{foo: "1", bar: "2"}, {foo: "2", bar:"3"}]
Q: Why is the "extra" property not stringified? How can I preserve the missing property in JSON.stringify()?
Upvotes: 1
Views: 4991
Reputation: 106365
Because data
is not just an Object - it's an Array. And when Arrays are json-stringified, all the non-numeric properties are discarded from result (as there's no way to represent them in [...]
notation anyway).
If you still want to see that property in JSON, you have to use plain Objects. You can bite the bullet and just "plain-objectify" the original array with { ... }
sugar:
const data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}];
data.extra = ["a", "b"];
JSON.stringify( {...data} );
// "{"0":{"foo":"1","bar":"2"},"1":{"foo":"2","bar":"3"},"extra":["a","b"]}"
... but beware, all those "0", "1" props will be seen inside your JSON as is, and that's not the best of views. It's usually cleaner just to use additional property:
const data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}];
const extra = ["a", "b"];
const output = {
data,
extra
};
JSON.stringify(output);
// "{"data":[{"foo":"1","bar":"2"},{"foo":"2","bar":"3"}],"extra":["a","b"]}"
Upvotes: 3
Reputation: 120
{...} is used to define a single object, while the other [...] is array and is used to define a sequence of either objects, values or lists ...
objects are defined as such {key:object or list or value , ...} list ares nothing more than a sequence of either objects or lists or values, [objects or list or values, ... ]...
try to use single object and not array.
Upvotes: 0
Reputation: 2035
your json is Array but you put one key to them
if you want to use it with keyword you should use :
var data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}];
data.push(["a", "b"]) ;
console.log(data)
// [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}, extra: ["a", "b"]]
console.log(JSON.stringify(data));
//[{foo: "1", bar: "2"}, {foo: "2", bar:"3"}]
Upvotes: 0
Reputation: 111
You can put the extra:[ ... ] inside { } wgich will make at in object. Then you can stringify it.
Upvotes: 0