繁体   English   中英

从数组值创建json对象数组

[英]Create array of json objects from array values

我有一个阵列

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

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

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

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

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

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

然后,您可以使用JSON.stringfynameObjs如果你确实需要JSON。

这是一个小提琴

为什么不呢?

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

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

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

小提琴

如果你以后不需要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]};
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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