[英]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. 我尝试了.replace(/"/g, "");
但是我发现replace不是一个函数。
JSON.stringify and JSON.parse didn't help me and a for loop JSON.stringify和JSON.parse对我和for循环没有帮助
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 这就是我的json的样子
{"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"]
}
You can use map
in combination with Object.keys
like this: 您可以将map
与Object.keys
结合使用,如下所示:
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. 谢谢@Rayon。
You could sort the keys (to maintain alphabetical order) and apply a replace for changing the comma to point and a casting to number. 您可以对键进行排序(以保持字母顺序),并应用替换以将逗号更改为指向点并将转换为数字。
var object = { "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"] }, array= Object.keys(object).sort().map(function(k) { return object[k].map(function (a) { return +a.replace(/,/g, ''); }); }); console.log(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.