简体   繁体   English

从数组值创建json对象数组

[英]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. 我已经尝试过循环并手动添加{和}但循环最终变得很大,但我觉得像JSON.stringify之类的东西将是'正确'的方式。

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. 然后,您可以使用JSON.stringfynameObjs如果你确实需要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... 如果你以后不需要names ......

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

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

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