jQuery: Convert string with comma separated values to specific JSON format

前端 未结 4 1312
情歌与酒
情歌与酒 2020-12-30 08:38

I\'ve been losing hours over something that might be trivial:

I\'ve got a list of comma-separated e-mail addresses that I want to convert to a specific JSON format,

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 09:04

    How about:

    var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me',
        obj = [],
        parts = to.split(",");
    
    for (var i = 0; i < parts.length; i++) {
        obj.push({email:parts[i]});
    }
    
    //Logging
    for (var i = 0; i < obj.length; i++) {
        console.log(obj[i]);
    }
    

    Output:

    Object {email: "bigbadwolf@grannysplace.com"}
    Object {email: "hungry@hippos.com"}
    Object {email: "youtalkin@to.me"}
    

    Demo: http://jsfiddle.net/tymeJV/yKPDc/1/

提交回复
热议问题