score:2

Accepted answer

You have to reassign the selection:

selection = selection.enter()
  .append("div")
  .classed("person", true)
  .merge(selection);

Also, you cannot use the first argument like that, you have to pass an function to the methods:

selection.append("p")
  .html(d=>d.name);

selection.append("p")
  .html(d=>d.age);

Here is your code with those changes:

var array = [{
    name: "John",
    age: 31
  },
  {
    name: "Mark",
    age: 29
  },
]

var selection = d3.select("#wrapper")
  .selectAll("div")
  .data(array);

selection = selection.enter()
  .append("div")
  .classed("person", true)
  .merge(selection);

selection.append("p")
  .html(d=>d.name);

selection.append("p")
  .html(d=>d.age);

selection.exit().remove();
<script src="https://d3js.org/d3.v5.min.js"></script>
<div id="wrapper"></div>

Finally, given the information you shared in your comment, the first choice to fix your code seems to be creating a nested enter/update/exit selection.

However, on a second thought, because your objects don't have nested arrays, a way simpler solution is appending the <p> elements in the enter selection and updating them in the update selection.

Here is a snippet demonstrating this, with 3 different data arrays:

var array = [{
    name: "John",
    age: 31
  },
  {
    name: "Mark",
    age: 29
  },
]

function display() {
  var selection = d3.select("#wrapper")
    .selectAll("div")
    .data(array);

  var selectionEnter = selection.enter()
    .append("div")
    .classed("person", true);

  selectionEnter.append("p")
    .classed("name", true)
    .html(d => d.name);

  selectionEnter.append("p")
    .classed("age", true)
    .html(d => d.age);

  selection.exit().remove();

  selection.select(".name")
    .html(d => d.name);

  selection.select(".age")
    .html(d => d.age);
}

display();
setTimeout(function() {
  array = [{
      name: "John",
      age: 31
    },
    {
      name: "Mark",
      age: 29
    },
    {
      name: "Andrew",
      age: 24,
    }
  ];

  display();
}, 2000)

setTimeout(function() {
  array = [{
      name: "John",
      age: 21
    },
    {
      name: "Bob",
      age: 49
    }
  ];

  display();
}, 4000)
<script src="https://d3js.org/d3.v5.min.js"></script>
<div id="wrapper"></div>


Related Query

More Query from same tag