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

前端 未结 4 1313
情歌与酒
情歌与酒 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 08:47

    Try changing the loop to this:

        var JSON = [];
        $(pieces).each(function(index) {
            JSON.push({'email': pieces[index]});   
        });
    
    0 讨论(0)
  • 2020-12-30 08:55

    Try this ES6 Version which has better perform code snippet.

    'use strict';
    
    let to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';
    
    let emailList = to.split(',').map(values => {
        return {
            email: values.trim(),
        }
    });
    
    console.log(emailList);

    0 讨论(0)
  • 2020-12-30 09:03
    var json = [];
    var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';
    var toSplit = to.split(",");
    for (var i = 0; i < toSplit.length; i++) {
        json.push({"email":toSplit[i]});
    }
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题