-1

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"
    }
  ]
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
woodturn
  • 1
  • 4
  • 1
    You aren't working with JSON. JSON is a string that represents a serialised object. – Lee Taylor May 15 '22 at 22:59
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – jabaa May 15 '22 at 23:01

2 Answers2

0
  1. Create a data object
  2. Populate the inner hierarchy with values
  3. Add a tools array to data
  4. Create tool object and populate
  5. Push tool to the tools array
  6. 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);
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
0

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.
Scovetta
  • 3,112
  • 1
  • 14
  • 13