0

I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.

This is just my code with other variable because of reasons:

My Code:

for (var key in array) {
}

The JSON I want:

[{
    key: "One",
    y: 5
}, {
    key: "Two",
    y: 2
},];

Pseudo JSON:

[{
    key: key,
    y: array[key].data
},{
    key: key,
    y: array[key].data;
},];
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
TobiasW
  • 861
  • 3
  • 13
  • 36

4 Answers4

2

I don't understand what is 'array'. Is it an object or an array?

I think what you want might be this, if 'array' is an array:

var new_arr = [];

your_array.forEach( function(entry) {
  new_arr.push({key: entry, y: entry.data}); // you should change it according to your need. 
})

return JSON.stringify(new_arr);

Or if 'array' is just an object, you may need this:

var new_arr = [];

for (key in array) {
  new_arr.push({key: key, y: array[key].data}); // you should change it according to your need. 
}

return JSON.stringify(new_arr);
Yoshi
  • 54,081
  • 14
  • 89
  • 103
iplus26
  • 2,518
  • 15
  • 26
2

You can try this solution:

var data = [];
for (var key in array) {
  data.push({
    key :  key,
    y : array[key].data
  });
}

console.log(data);

But, what about Pseudo JSON:?

DEMO - See console (chrome) for output

Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40
0

JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax. Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.

Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:

var data = []
for (var key in array)
{
    data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...

If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.

Community
  • 1
  • 1
Neonit
  • 680
  • 8
  • 27
0

you can use following line to create an array of json

var jsonArr = [];

then you can create json object from following line

var obj = new Object();

put data in json object as following

obj['id'] = 123;
obj['name'] = 'ABC';

then put json object in json array as

jsonArr.push(obj);

you want to add multiple objects in json array then simply create json object and add one by one using push method.

[{"id":"123","name":"ABC"}]
dom
  • 1,086
  • 11
  • 24