admin管理员组文章数量:1333164
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. 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
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. 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
Share
Improve this question
asked Sep 6, 2016 at 22:04
Akanksha IyerAkanksha Iyer
1292 gold badges4 silver badges7 bronze badges
0
4 Answers
Reset to default 4You 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. 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 = 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;
}
本文标签: javascriptChange the data type in the array of ObjectsStack Overflow
版权声明:本文标题:javascript - Change the data type in the array of Objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742350420a2458378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论