user3891065 user3891065 - 3 months ago 10
Javascript Question

Create Json from two arays

I want to create one Json object from the two arrays using JavaScript or jQuery. The data saved in database in the following format:


clob_field_1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 etc etc ...

clob_field_2: 8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43,
8137.9, 8265.81, 8319.5, 8186.43 etc etc ...


Ideally, the outcome should looks like this:


[{"Item:" 1, "Value:" 8106.23}, {"Item:" 2, "Value:" 7856.49}, {"Item:" 3, "Value:" 8009.15}, {"Item:" 4, "Value:" 8121.78}, etc etc ...]


So what I've done, I've fetched the clobs fileds from the database using PL/SQL, so I can access it from the JavaScript. After that I declared 2 variables and set the object and want to loop through the data to create a nice pairs of data. This is my JavaScript code so far:

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81, 8319.5, 8186.43];
var obj = {};
for (var i = 0; i < a.length; i++) {
obj['Item:' + a[i]] = 'Value:' + b[i] + '}';
}
alert(JSON.stringify(obj));


But the outcome is awful and looks as follows:

{"Item:1":"Value:8106.23}","Item:2":"Value:7856.49}","Item:3":"Value:8009.15}","Item:4":"Value:8121.78}","Item:5":"Value:8082.8}","Item:6":"Value:8294.43}","Item:7":"Value:8137.9}","Item:8":"Value:8265.81}","Item:9":"Value:8319.5}","Item:10":"Value:8186.43}"}


The left curly brackets are missing from the pair 2 onwards, colons instead of coma, speech marks are in wrong place etc etc ... I believe there is a syntaxis error in my code and I cannot figure out what is it. Any help appreciated, Thanks in advance!

Answer

Create an array for your output and push new objects into it rather than setting them all in a single object.

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9,    8265.81, 8319.5, 8186.43];
var output = [];
for (var i = 0; i < a.length; i++) {
    output.push({'Item': a[i], 'Value': b[i]});
}
alert(JSON.stringify(output));