How do I build a nested object in Javascript dynamically?

So I was giving this some thought and realized that if the nested object is deep enough, or your nested objects were sufficiently heavy, then it could blow the stack using recursion.

So I thought to present you an iterative solution that works for any depth and object size without blowing the stack. This solution still runs in O(n) time like the recursive one, but improves space complexity from O(s + n) to O(n) – assuming n to be the size of the new object, and s to be the size of the recursive stack.

const arr1 = ['a', 'b', 'c']
const arr2 =  [1, 2, 3]

const obj = {}
let prevNode

for(let i = 0; i < arr1.length; i++){
  const key = arr1[i]
  const nextNode = {
      [key]: {
        terms: {
          fields: arr2[i]
        }
      }
    }

  if(!prevNode) {
    obj.aggs = nextNode
    prevNode = obj.aggs[key]
  } else {
    prevNode.aggs = nextNode
    prevNode = prevNode.aggs[key]
  }
}