1

I have am array like this:

var jsonObj = {
  "name": "my boards",
  "children": [
    {
      "name": "AAA",
      "children": [
        {
          "name": "AAA_2",
          "size": 422
        },
        {
          "name": "AAA_2",
          "size": 422
        },
        {
          "name": "AAA_2",
          "size": 422
        }
      ]
    },
    {
      "name": "BBB",
      "children": [
        {
          "name": "BBB_2",
          "size": 422
        },
        {
          "name": "BBB_2",
          "size": 422
        },
        {
          "name": "BBB_2",
          "size": 422
        }
      ]
    },
    {
      "name": "CCC",
      "children": [
        {
          "name": "CCC_2",
          "size": 422
        },
        {
          "name": "CCC_2",
          "size": 422
        },
        {
          "name": "CCC_2",
          "size": 422
        }
      ]
    }
  ]
}

And I want to use jquery to fill this object with values inside divs. I think I am getting the dots and brackets wrong. I am trying this:

function fill_object() {
  $.each($('.my_div'), function() {
    jsonObj.children["name"] = $(this.id).value();
    jsonObj.children.children["name"] = $(this.id).value();
  });
  return (jsonObj)
}

But I get the following error:

Uncaught TypeError: Cannot read property 'children' of undefined

I want to be able to add values to AAA, AAA_2, BBB, BBB_2, CCC and CCC_2

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Cybernetic
  • 12,628
  • 16
  • 93
  • 132

1 Answers1

1

As you mentioned in comments that this is what you were looking for (was not answering as I was not sure about your requirements)

So the thing is that you need nested loops like

for(var i = 0; i < jsonObj.children.length; i++) {
    console.log(jsonObj.children[i].name); //outputs name

  for(var j = 0; j < jsonObj.children[i].children.length; j++) {
    console.log(jsonObj.children[i].children[j].name); //outputs nested children names
  }
}

Over here, am looping jsonObj.children first, and later, I am nesting another for loop to iterate over nested array which further has objects with name as a key.

You can do a minor optimization here by doing something like

for(var i = 0, l = jsonObj.children.length; i < l; i++)

So that we only count the length of your array once. You can do the same for your nested loop.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278