G Boomanikandan G Boomanikandan - 11 days ago 7
Javascript Question

Array conversion gives string instead of array

I want to convert two arrays into another array format.

Here is my code:



var array1 = [ "Kolkata", "Begumpet", "Bellary"];

var array2 = [[[20,"Kolkata1"],[10,"Kolkata2c"]],
[[0,"Begumpet1"],[10, "Begumpet2e"]],
[[30, "Bellary1"],[0, "Bellary2a"]]]

console.log(array2);
var resultvalue = [];
for (i = 0; i < array2.length; i++) {
var result = "";
var m = 0;
for (j = 0; j < array2[i].length; j++) {
if(m==0){
result += "label: '" + array1[i] + "',";
m++;
}
result += " '" + array2[i][j][1] + "': " + array2[i][j][0] + ", ";
}
resultvalue.push(result);
}
console.log(resultvalue);





It's producing what I want, except that the result is a string, while I need the actual array.

The expected output object should be like this:

dataset = [
{label:"Kolkata", "Kolkata1":20, "Kolkata2c":10},
{label:"Begumpet", "Begumpet1":0, "Begumpet2e":10},
{label:"Bellary", "Bellary1":30, "Bellary2a":0},
];

Answer

You could iterate array2 and map a new object for each entry.

var array1 = ["Kolkata", "Begumpet", "Bellary"],
    array2 = [[[20, "Kolkata1"], [10, "Kolkata2c"]], [[0, "Begumpet1"], [10, "Begumpet2e"]], [[30, "Bellary1"], [0, "Bellary2a"]]],
    dataset = array2.map(function (a, i) {
        var o = { label: array1[i] };
        a.forEach(function (b) {
            o[b[1]] = b[0];
        });
        return o;
    });

console.log(dataset);
.as-console-wrapper { max-height: 100% !important; top: 0; }