从数组值创建json对象数组

时间:2014-02-04 18:08:54

标签: javascript arrays json sorting

我有一个数组

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

如何让数组成为像这样的对象数组?

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

我尝试过循环并手动添加{和}但是循环最终变得很大,但我觉得像JSON.stringify这样的东西会是'正确'的方式。

4 个答案:

答案 0 :(得分:2)

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

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

如果您确实需要JSON,则可以在JSON.stringfy上使用nameObjs

这是fiddle

答案 1 :(得分:1)

为什么不呢?

// 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
}

答案 2 :(得分:0)

我所知道的最简单的方法是:

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

这是一个循环,但不是那么大

你做了一个功能:

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

Fiddle

答案 3 :(得分:0)

如果您之后不需要names ......

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

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

甚至......

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