title: Create nested object in javascript
body: <p>I want to create a nested object in javascript as following.</p>
  <pre><code>const data = {
    name: 'Context 1',
    children: [
      {
        name: 'Option 1',
        children: [
          {
            name: 'Context',
            children: [
              {
                name: 'Option'
              },
               {
                 name: 'Option'
               }
            ]
          }
        ]
      },
      {
        name: 'Option 2',
        children: [
          {
            name: 'Context 1',
            children: [
              {
                name: 'Option'
              },
              {
                name: 'Option'
              }
            ]
          }
        ]
      }
    ]
  }
  </code></pre>
  <p>The object starting from <code>Context 1</code>, each 'Context' will have 2 or 3 <code>options</code> and every <code>option</code> will have one <code>Context</code> and that <code>Context</code> can again have 2/3 <code>options</code> and so on.</p>
  <blockquote>
  <p>The user will have control to define upto which level are we going to extend the object.</p>
  </blockquote>
  <blockquote>
  <p>By level, its defined like this
  <a href="https://i.stack.imgur.com/BZCAK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BZCAK.png" alt="enter image description here" /></a></p>
  </blockquote>
  <p>I tried something like this with <strong>ReactJs</strong> but it didn't work.</p>
  <p>State:</p>
  <pre><code>this.state = {
     myContentIndex: 1,
     myLevelIndex: 0,
     levels: 3,
  }
  </code></pre>
  <p>My functions:</p>
  <p>Here I called <code>addContext([], 3)</code></p>
  <pre><code>addContext = async (data, options) =&gt; {
    const myData = [...data]
    const { myContextIndex, myLevelIndex, levels } = this.state
    await myData.push(this.getDataNodeObject('Context', myContextIndex))
    this.setState({ myContextIndex: myContextIndex + 1 }, async () =&gt; {
      var nextData = await this.setOptions(myData[0].children, options)
      if (myLevelIndex &lt;= levels) {
        this.setState({ myLevelIndex: myLevelIndex + 1 }, async () =&gt; {
          await nextData.forEach(item =&gt;
            this.addContext(item.children, options)
          )
        })
      }
      await nextData.forEach(item =&gt; myData[0].children.push(item))
    })
    return myData
  }
  
  setOptions = async (data, options) =&gt; {
    let arr = [...data]
    for (let i = 0; i &lt; options; i++) {
      await arr.push(this.getDataNodeObject('Option', i + 1))
    }
    return arr
  }
  
   getDataNodeObject = (name, index) =&gt; ({
     name: `${name + ' ' + index}`,
     children: [],
     index: index
   })
  </code></pre>
  <p>Is there a way to do it with all these conditions?</p>