Converting string array to Name/Value object in javascript

后端 未结 4 1584
甜味超标
甜味超标 2020-12-11 09:10

I currently am dealing with a Web Service that is returning an array of strings to the client. From here I would like to take this array of strings and convert it into an o

相关标签:
4条回答
  • 2020-12-11 09:42

    You could do something like the following:

    var input = ["one", "two", "three"], 
        output = [],
        obj;
    
    for (var i = 0; i < input.length; i++)
    {
        obj = { "value" : input[i] };
    
        output.push(obj);
    
    }
    

    Link to the fiddle

    0 讨论(0)
  • 2020-12-11 09:46
    var final = $.map(result, function(val) {
        return { value: val };
    });
    

    Alternatively you can use the ES5 alternative

    var final result.map(function(val) {
        return { value: val };
    });
    

    Or a simple iteration.

    var final = [];
    for (var i = 0, ii = result.length; i < ii; i++) {
        final.push({ value: result[i] });
    }
    
    0 讨论(0)
  • 2020-12-11 09:46

    I don't think jQuery has to be used here.

    var result = ["test", "hello", "goodbye"];
    var final = [];
    for(var i = 0; i < result.length; i++) {
        final.push({value: result[i]})
    }
    
    0 讨论(0)
  • 2020-12-11 09:59

    I haven't tested this but you can do something like

    $(result).map(function(){return {'value':this}});

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