Reputation: 23
I don't know why I get such a weird structure. To understand the code: I get from an input field the value (request.body.id). It's a JSON so I parse it(should have the same structure as var data). Then I push it in my array. Thereafter I push my object (data) in the array. So it should include the old object and the new object (data). Then I stringify my array and send it back to client. Thereafter I do the same cycle a few times. I can the in the browser inspection my JSON, but it has a weird structure after the first cycle (example below). And I can't access the objects of the array with this structure. Maybe you have a better solution, so I don't have this structure. I want the normal structure of array of objects like this: [{"a":1,"b":1,"c":1},{"a":12,"b":12,"c":12},{"a":13,"b":13,"c":13}]
.
[{"a":1,"b":1,"c":1}]
Structure after first time sending back to client.
`[[[{"a":1,"b":1,"c":1}],{"a":1,"b":1,"c":1}],{"a":1,"b":1,"c":1}]` Structure after 3 times.
var array = [];
var json = JSON.parse(request.body.id);
array.push(json);
var data = {a:input1,b:input2,c:input3};
array.push(data);
var send = JSON.stringify(array);
Upvotes: 0
Views: 1880
Reputation: 192507
You are creating a new array (array
var), and then you push the parsed JSON, which seems to be an array as well into array
, and so on.
Since the parsed JSON is already an array, just push data
into it:
var array = JSON.parse(request.body.id); // parse and assign to array
array.push({ a: 1, b: 1, c: 1 }); // push new data
var send = JSON.stringify(array); // stringify back
Upvotes: 3