[英]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.stringfy
上nameObjs
如果你確實需要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.