[{
id: '1',
name: '小王',
desc: '小王描述'
}, {
id: '2',
name: '小强',
desc: '小强描述'
}, {
id: '6',
name: '小红',
desc: '小红描述'
}, {
id: '9',
name: '小东',
desc: '小东描述'
}]
This is the data sent back from the background. How can I use a for
loop to turn the id
inside into a number? I don’t know how to write it, so embarrassed
过去多啦不再A梦2017-06-26 10:57:17
The key point is to convert the string into a numerical value, either parseInt
or Number
can be converted. Or let the background pass the numerical type directly. Question: This is data obtained from the backend and is generally rendered to the page. Why does it need to be converted into a numerical value?
天蓬老师2017-06-26 10:57:17
Like this
function change(items){
items= items|| [];
for( var i = 0,item; item = items[i++]; ){
item.id *= 1;
}
return items;
}
var result = change(/*你需要弄的*/);
怪我咯2017-06-26 10:57:17
//方法一
for(var i=0,len=arr.length;i<len;i++){
arr[i].id=parseInt(arr[i].id)
}
//方法二
arr.map(function(item){return {desc:item.desc,id:parseInt(item.id),name:item.name}})
//es6写法
arr.map(item=>{{desc:item.desc,id:parseInt(item.id),name:item.name}})
代言2017-06-26 10:57:17
var result = arr.map(item => {item.id = parseInt(item.id); return item;});
But because of the object reference type, the id in the original array arr is also a numeric value
学习ing2017-06-26 10:57:17
Let’s talk about the idea first:
1. First traverse the array
2. Traverse the object
3. Add attribute key-value pairs and delete old key-value pairs
Code below:
var jsonData = [{
id: '1',
name: '小王',
desc: '小王描述'
}, {
id: '2',
name: '小强',
desc: '小强描述'
}, {
id: '6',
name: '小红',
desc: '小红描述'
}, {
id: '9',
name: '小东',
desc: '小东描述'
}];
var i = 0;
for (; i < jsonData.length; i++) {
for (var name in jsonData[i]) {
if (name === 'id') {
jsonData[i][i] = jsonData[i][name];
delete jsonData[i][name];
}
}
}