3

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 object that gives each string a name so to reference it later.

So start with this:

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

And I would like to end up with this:

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

I use jquery. Is there a easy to accomplish this?

4 Answers 4

7
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] });
}
Sign up to request clarification or add additional context in comments.

Comments

4

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]})
}

3 Comments

for(i in result) would give the same answer with less typing
@Bryce Siedschlaw: Be careful with that, prototype functions would suddenly be in the array too.
Hmm, interesting. Figured there would be a caveat.
2

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

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

1 Comment

Try this: var result = $(result).map(function() { return {'value': this}; });
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.