Convert string array to Name / Value object in javascript

I am currently dealing with a web service that returns an array of strings to a client. From here, I would like to take this array of strings and convert it to an object that gives each row a name to refer to it later.

So start with this one:

var result = ["test", "hello", "goodbye"];

And I would like to end up with:

var final = [{'value': "test"}, {'value': "hello"}, {'value': "goodbye"}];

I am using jquery. Is it easy to do?

+3
source share
4 answers
var final = $.map(result, function(val) {
    return { value: val };
});

Alternatively you can use alternative ES5

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] });
}
+7
source

I don't think jQuery should be used here.

var result = ["test", "hello", "goodbye"];
var final = [];
for(var i = 0; i < result.length; i++) {
    final.push({value: result[i]})
}
+4
source

, -

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

+2

- :

var input = ["one", "two", "three"], 
    output = [],
    obj;

for (var i = 0; i < input.length; i++)
{
    obj = { "value" : input[i] };

    output.push(obj);

}

fiddle

+2
source

All Articles