js遍历多级带子级是children的数组 查找是否存在checked属性是true的

function findCheckedItem(arr) {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item.checked === true) {
      return true;
    }
    if (item.children && item.children.length > 0) {
      const found = findCheckedItem(item.children);
      if (found) {
        return true;
      }
    }
  }
  return false;
}

// 示例数据
const data = [
  {
    name: "Item 1",
    checked: false,
    children: [
      {
        name: "Sub Item 1",
        checked: true,
        children: []
      },
      {
        name: "Sub Item 2",
        checked: false,
        children: []
      }
    ]
  },
  {
    name: "Item 2",
    checked: false,
    children: []
  }
];

const hasCheckedItem = findCheckedItem(data);
console.log(hasCheckedItem); // true

你可能感兴趣的:(js,javascript)