1

I have an array

var names = ["bob", "joe", "jim"];

How do I get the array to be a array of objects like so?

var nameObjs = [{"name":"bob"},{"name":"joe"},{"name":"jim"}];

I've tried doing a loop and adding { and } manually but the loop just ends up getting to big, but I feel like something like JSON.stringify would be the 'correct' way of doing it.

1
  • What do you mean "the loop just ends up getting to [sic] big"? Why don't you share what you tried? Commented Feb 4, 2014 at 18:10

4 Answers 4

2
var names = ["bob", "joe", "jim"];

var nameObjs = names.map(function(item) {
    return { name: item };
});

You can then use JSON.stringfy on nameObjs if you actually need JSON.

Here's a fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Damn you, posted while I was finishing typing the last few characters of this exact answer.
@tenub: Happens to me all the time.
1

Why not this?

// Get your values however rou want, this is just a example
var names = ["bob", "joe", "jim"];

//Initiate a empty array that holds the results
var nameObjs = [];

//Loop over input.
for (var i = 0; i < names.length; i++) {
    nameObjs.push({"name": names[i]}); //Pushes a object to the results with a key whose value is the value of the source at the current index
}

Comments

0

The easiest way I know of is:

var names = ["bob", "joe", "jim"];
var namesObjs = []
for (var i = 0; i<names.length; i++) {namesObjs.push({name:names[i]})}

This is with a loop, but not that big

You make a function to do this:

function toObj(arr) {
    obj=[];
    for (var i = 0; i<arr.length; i++) {obj.push({name:arr[i]})}
    return obj;
}

Fiddle

Comments

0

If you don't need names afterward...

var names = ["bob", "joe", "jim"],
  nameObjs = [];

while (names.length) {
  nameObjs.push({
    'name': names.shift()
  });  
}

or even...

var names = ["bob", "joe", "jim"],
  n;
for (n in names) {
  names[n] = {'name': names[n]};
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.