简体   繁体   中英

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.

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

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM