jimakos17 jimakos17 - 4 months ago 8
Javascript Question

Convert an object of arrays into an array of arrays in JavaScript

I have an object with arrays, each of which has numbers with double quotes, and I'd like to convert it into an array of arrays without double quotes.

This

> Object { CategoryA: Array[182], CategoryB: Array[180],
> CategoryC: Array[182], CategoryD: Array[171],
> CategoryE: Array[182], CategoryF: Array[183] }


to

Array [ Array[182], Array[182], Array[182], Array[182], Array[182], Array[182] ]


I tried
.replace(/"/g, "");
but I'm getting that replace is not a function.

JSON.stringify and JSON.parse didn't help me and a for loop

for (var i = 0; i < data.length; i++) {
data2[i] = data[i].replace(/"/g, "");
}
console.log(data2);


returns double quotes.

UPDATE

This is how my json looks like

{"CategoryA": ["297,239", "277,227", "279,310", "297,766"],
"CategoryB": ["15,479,207", "14,845,266", "15,454,549"],
"CategoryC": ["285,648", "295,982", "300,306", "302,508"]
}

Answer

You can use map in combination with Object.keys like this:

var result = Object.keys(yourObject).sort().map(function(key) {
    return yourObject[key].map(function(num) {
        return +num.replace(/,/g, '');
    });
});

Please note that the comma , in your numbers it's for formatting, not a floating point.

var yourObject = {"CategoryA": ["297,239", "277,227", "279,310", "297,766"],
 "CategoryB": ["15,479,207", "14,845,266", "15,454,549"],
 "CategoryC": ["285,648", "295,982", "300,306", "302,508"]
} ;

var result = Object.keys(yourObject).sort().map(function(key) {
    return yourObject[key].map(function(num) {
      return +num.replace(/,/g, '');
    });
});

console.log(result);

Thank you @Rayon.