Skip to content
Advertisement

Create a Listed (Nested) Element in a Javascript object

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"
    }
  ]
}

Advertisement

Answer

  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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement