如何在Javascript中将其转换为:
[
{
"label": "Purok I",
"y": "1"
},
{
"label": "Purok II",
"y": "1"
},
{
"label": "Purok III",
"y": "2"
}
]
收件人:
[
{
label: "Purok I",
y: 1
},
{
label: "Purok II",
y: 1
},
{
label: "Purok III",
y: 2
}
]
有帮助吗?
答案 0 :(得分:3)
使用map
将所有字符串化的数字转换为非字符串化的数字,并进行如下分解:
const data = [
{
"label": "Purok I",
"y": "1"
},
{
"label": "Purok II",
"y": "1"
},
{
"label": "Purok III",
"y": "2"
}
];
const numbered = data.map(({ label, y }) => { return {label, y: parseInt(y)}});
console.log(numbered);
.as-console-wrapper { max-height: 100% !important; top: auto; }
原来不可能制作无字符串的属性名称:
var obj = {
foo: "bar",
one: 1
};
console.log(obj);
答案 1 :(得分:3)
let p = [
{
"label": "Purok I",
"y": "1"
},
{
"label": "Purok II",
"y": "1"
},
{
"label": "Purok III",
"y": "2"
}
]
let result = p.map(function(x) {
x.y = Number(x.y);
return x;
});
console.log(result);
答案 2 :(得分:2)
此方法将自动更新对象中的所有数字类型。
let arr = [{
"label": "Purok I",
"y": "1"
},
{
"label": "Purok II",
"y": "1"
},
{
"label": "Purok III",
"y": "2",
"example": "432.23"
}
];
// Map over your array of objects
arr = arr.map(obj => {
// Map over all the keys in your object
Object.keys(obj).map(key => {
// Check if the key is numeric
if (!isNaN(obj[key])) {
obj[key] = +obj[key];
}
})
return obj;
});
console.log(arr);