javascript / jquery - creating an object in a particular format from a loop

此生再无相见时 提交于 2019-12-08 06:40:17

问题


I'm trying to get some data into this format, for use with a templating system called mustache:

{
  "repo": [
    { "name": "resque" },
    { "name": "hub" },
    { "name": "rip" },
  ]
}

and what I currently have is this:

for (childIndex in scenes[sceneID].children) {  
    childSceneID = scenes[sceneID].children[childIndex];
    childScene = scenes[childSceneID];
}

So I somehow need to make each childScene the "name" in the "repo" object. Does anyone know how to do this? This is the mustache documentation:

http://mustache.github.com/mustache.5.html


回答1:


Is this what you meant?:

var repo = [];

for (childIndex in scenes[sceneID].children) {  
    childSceneID = scenes[sceneID].children[childIndex];
    childScene = scenes[childSceneID];
    repo.push({"name": childScene});
}

var theobj = { "repo": repo };



回答2:


I just put this here

var repo = new Object();
var table = new Object();
repo["repo"] = table;
table["name1"] = "resque";
table["name1"] = "hub";
table["name1"] = "rip";


来源:https://stackoverflow.com/questions/7071193/javascript-jquery-creating-an-object-in-a-particular-format-from-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!