Jackson Geller
Jackson Geller

Reputation: 189

Create array of json objects from array values

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.

Upvotes: 1

Views: 32

Answers (4)

reergymerej
reergymerej

Reputation: 2417

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

Upvotes: 0

Yannick
Yannick

Reputation: 372

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

Upvotes: 0

Kroltan
Kroltan

Reputation: 5156

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
}

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

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

Upvotes: 2

Related Questions