Linking up JSON data to g elements in d3

So I am stuck on a problem in d3. I have this JSON file

{
  "nodes": [
    {"container": "Container 1", "x" : 0, "y" : 0, "px" : 0, "py": 0, "col" : 1, "row" : 0, "height" : 100, "width" : 100},
    {"container": "Container 2", "x" : 100, "y" : 0, "px" : 0, "py": 0, "col" : 1, "row" : 0, "height" : 100, "width" : 100}]
}

I make elements correspond to the length of the nodes inside JSON. Inside each element there is going to be a element that corresponds to the data depicted above for container 1 and so on another element that corresponds to container 2.

My desired file frame be:

<svg>
    <g>
       <rect>Container 1</rect>
    </g>
    <g>
       <rect>Container 2></rect>
    </g>
</svg>

Where I am lost is this

gCode.append("rect").data(graph.nodes)
            .enter()
            .attr('class', 'blob')
            .style("border", "20px solid")

Since I won’t know the size of the JSON file and I am wondering whether as the g elements are produced that the first element would correspond to container 1 and then so on.

Things I have tried

I was implementing a forEach function but was advised not to since it gives problems later down the line and I am suspecting it could be the same case here.



There are a few things happening here, and I may be misunderstanding the question (I looked at your previous question to better understand the context).

First, “I am wondering whether as the g elements are produced that the first element would correspond to container 1”

When entering data with d3, items are appended in the order provided – so the first element created have the data of the first item in the data array bound to it. If your data is already in order, then they will append in order.

If your <g> elements already exist in the selection that you are appending <rect>s to, then the first item in the dataset will be bound to a <rect> in the first <g> in the selection.

Second (if I read your problem correctly), if you are trying to create a <rect> in each <g> using the same data – then why not append a <g> for each item in the dataset, and then, using data bound to each <g>, append a <rect> to each <g>. This would give you a structure like you want:

<svg>
  <g>
     <rect class="Container1" x="0" y="0" width="100" height="100"></rect>
  </g>
  <g>
      <rect class="Container2" x="100" y="100" width="100" height="100"></rect>
  </g>
</svg>

And could be done quite easily:

This approach links(binds) the data in the json to the g, which is easily used to create new child elements in each g, which based on your title and your goal, seems like what you are aiming for.