JSFiddle - React, Tailwind, and code Playground

by amrendra kumar

JavaScript

const updateDepthAndCheckedCount = (data, depth = 0) => {
  data.forEach((item) => {
    item.depth = depth;

    let checkedCount = item.checked === true ? 1 : 0;

    if (item.children && item.children.length > 0) {
      const childData = updateDepthAndCheckedCount(item.children, depth + 1);
      item.children = childData;
      checkedCount += childData.reduce((acc, child) => acc + child.checkedCount, 0);
    }

    item.checkedCount = checkedCount;
  });

  return data;
};




const updatedArray = updateDepthAndCheckedCount(array);
console.log(updatedArray); // Displays the updated array wit