My question comes from this answer to a similar question. The comment below the answer sums up my question
how would the code look like if you would like to give depth to the tree? Like for name i would like to give name.firstname and name.lastname. Would I need to define name as var?
This is my current code
var jsonOutput = new Object();;
jsonOutput.workflowID=1234;
jsonOutput.author="jonny"
I want to create a javascript object that looks like the below. I am stuck with creating the list of Tools. How would I do this?
{
"workflowID": "1234",
"author": "jonny",
"tools": [
{
"toolid": "543",
"type": "input",
},
{
"toolid": "3423",
"type": "input",
},
{
"toolid": "1234",
"type": "merge",
"on": "Channel Name"
}
]
}
CodePudding user response:
- Create a
data
object - Populate the inner hierarchy with values
- Add a
tools
array todata
- Create
tool
object and populate - Push
tool
to thetools
array - Repeat
var data = {};
data.workflowID = 1234;
data.author = "jonny";
data.tools = [];
let tool = {};
tool.toolid = 543;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = 3423;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = "1234";
tool.type = "merge";
tool.on = "Channel Name";
data.tools.push(tool);
console.log(data);
CodePudding user response:
Technically, to create a more complex object, you can just do something like:
tool543 = new Object();
tool543.toolid = "543";
tool543.type = "input";
jsonOutput.tools = []; // Now .tools is an empty array
jsonOutput.tools.push(tool543); // And now you're appending to it.