0

Goal: get all table row (cell) data and add to an array

Problem: if there are more than 1 row, it over-writes previously added array entries in stead of adding it to the end of the array. This causes the array to have the last table row dataset duplicated/triplicated/etc (as many rows as there exist in table)

Setup: I have a dynamic html table where a user can add rows by entering a user name and age and click the Add button. The Load button must get the table body elements and populate an object, where after a for loop must get the innerText, update the object and push() the object to the array. But this is the result: Screenshot of console.log of array

let roleArr = [];
loadBtn.addEventListener("click", () => {
  roleTableData();
});

function roleTableData() {
  let test = tblRows.children;
  const collectRoles = {
    uName: "",
    uAge: "",
  };

  for (let i = 0; i < test.length; i++) {
    collectRoles.uName= test[i].children[0].innerText;
    collectRoles.uAge= test[i].children[1].innerText;
    roleArr.push(collectRoles);
  }
}
  • Why not refactor the code to where you're adding the name and age as an object to the array first and then using the array to create the table? Then instead of managing the html you're only managing the data, letting a template create a new row each time an object is created. – Chris Jul 01 '21 at 21:49
  • Thank you for the advise @Chris. I am currently researching that option. It makes much more sense doing the way you suggested. – VonnScript Jul 03 '21 at 18:11

1 Answers1

0

Since you're using the same collectRoles object for each irraration, you are redefining all the objects, since they are references of the same object.

You can research "reference vs value in JavaScript" to better understand why this is so.

Here is how I would write your roleTableData function:

function roleTableData() {
  roleArr = [...tblRows.children].map(tr => {
    return {
      uName: tr.children[0].innerText,
      uAge: tr.children[1].innerText
    };
  });
}
H K
  • 1,062
  • 8
  • 10
  • Thank you for responding. I am researching the spread operator now to understand what your suggested code is doing exactly. Once understood, I will respond again – VonnScript Jul 03 '21 at 18:12
  • In this case, the spread operator is used to covert a `nodeList` (which is array-like, but can not be iterated with the `map` array method.) to an actual array. See this SO question: https://stackoverflow.com/questions/7459704/in-javascript-what-is-the-best-way-to-convert-a-nodelist-to-an-array – H K Jul 06 '21 at 11:39