[英]Change the data type in the array of Objects
I have the array of Objects as follows 我有如下的对象数组
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
Value: "34343"
1:Object
id=2
name:'david'
Value: "2332"
As you can see, the Value field in the array of Objects is a string. 如您所见,Objects数组中的Value字段是一个字符串。 I want all these to be converted to a number instead.
我希望所有这些都转换为数字。
The final data should look like this. 最终数据应如下所示。 can someone let me know how to achieve this please.
有人可以让我知道如何实现这一目标。
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
Value: 34343
1:Object
id=2
name:'david'
Value: 2332
You can convert a number literal into a number using a +
prefix: 您可以使用
+
前缀将数字文字转换为数字:
var input = { Results: [{ id: 1, name: "Rick", Value: "34343" }, { id: 2, name: 'david', Value: "2332" }] } for (var i = 0; i < input.Results.length; i++) { input.Results[i].Value = +input.Results[i].Value; } console.log(input);
Just call .parseInt() on each of your "Value" fields. 只需在每个“值”字段上调用.parseInt()。 For example: `
例如:
for(var i in Results){
if(Results[i].Value != ""){
Results[i].Value = parseInt(Results[i].Value);
}`
}
You can map data.Results
and use parseInt()
on the Value properties: 您可以映射
data.Results
并在Value属性上使用parseInt()
:
data.Results = data.Results.map(function(d) {
d.Value = parseInt(d.Value, 10);
return d;
});
console.log(data);
However, why do you need this? 但是,为什么需要这个呢? Maybe you should consider to do the parsing once you actually access the data...
也许您应该在实际访问数据后考虑进行解析...
If you can do this in a basic way, it will look like: 如果您可以通过基本方式做到这一点,它将看起来像:
function convertArrayValues (array) { // obj.Results goes here
// cloning can be ommited
var array = JSON.parse(JSON.stringify(array));
for(var i = 0; i < array.length; i++) {
array[i].Value = parseFloat(array[i].Value);
}
return array;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.