search

Home  >  Q&A  >  body text

javascript - Issues about loop traversal of arrays

[{
    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

给我你的怀抱给我你的怀抱2793 days ago851

reply all(6)I'll reply

  • 过去多啦不再A梦

    过去多啦不再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?

    reply
    0
  • 天蓬老师

    天蓬老师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(/*你需要弄的*/);

    reply
    0
  • 怪我咯

    怪我咯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}})
    

    reply
    0
  • 代言

    代言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

    reply
    0
  • 迷茫

    迷茫2017-06-26 10:57:17

    Just use parseInt to transfer directly and it will be ok

    reply
    0
  • 学习ing

    学习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];
                    }
                }
            }

    reply
    0
  • Cancelreply