[英]JavaScript JSON Object arrays
Folks, I need to generate the following .json file and return to the browser: 伙计们,我需要生成以下.json文件并返回浏览器:
"hosts": [
{
"project": [
{
"service": [
{
"role": [
{
"env": [
{
"name": "Her blog",
"cmd": "ssh username@blog2.example.com"
},
{
"name": "Her foo",
"cmd": "ssh username@blog2.example.com"
}
]
}
]
}
]
}
]
},
]
I am lost at how to loop through several local lists and generate this Object. 我迷失在如何遍历几个本地列表并生成此对象的迷茫。 I loop through a few lists to instantiate the Object like so:
我遍历几个列表来实例化对象,如下所示:
_.each(instances, function (instance) {
_.each(projects, function (project) {
_.each(services, function (service) {
_.each(roles, function (role) {
_.each(environments, function (environment) {
if (_.isUndefined (projectObject[project])) {
projectObject[project] = {};
}
if(_.isUndefined(projectObject[project][service])) {
projectObject[project][service] = {};
}
...
});
In the next iteration, i build objects of each instance, but they dont show up in the browser, ie its an empty array, not an object. 在下一次迭代中,我将构建每个实例的对象,但是它们不会显示在浏览器中,即其为空数组,而不是对象。
_.extend(projectObject[project][service][role][environment],i); //doesnt work
As you can see, the requirement is to have Arrays of Objects. 如您所见,要求是具有对象数组。
How should I approach this problem? 我应该如何解决这个问题?
To simplify things look at this, lets say you have this object: 为了简化起见,让我们说您有这个对象:
var Myhosts = {"hosts": [
{
"project": [
{
"service": [
{
"role": [
{
"env": [
{
"name": "Her blog",
"cmd": "ssh username@blog2.example.com"
},
{
"name": "Her foo",
"cmd": "ssh username@blog2.example.com"
}
]
}
]
}
]
}
]
},
]}
To get the name and cmd of the env you do this: 要获取环境的名称和命令,请执行以下操作:
Myhosts.hosts[0].project[0].service[0].role[0].env[0].name === "Her blog"
Myhosts.hosts[0].project[0].service[0].role[0].env[0].cmd === "ssh username@blog2.example.com"
Myhosts.hosts[0].project[0].service[0].role[0].env[1].name === "Her foo"
So if you have more than one object in any of the arrays, where you see [0] just replace 0 with a variable like x and loop through each dimension. 因此,如果在任何一个数组中都有多个对象,则看到[0]只需将0替换为x等变量并遍历每个维度。 Let me know if this helps.
让我知道是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.