JavaScript 嵌套对象数组操作全攻略:轻松提取 children 值,掌握复杂数据结构处理》 《前端开发必备技能:JS 处理嵌套对象数组的多种方法,新手也能快速上手》 《JavaScript

### 效果图


🌟【定制化开发服务,让您的项目领先一步】🌟

如有需求,直接私信留下您的联系方式。谢谢。
我的邮箱:2351598671@qq.com


博客正文

JavaScript 嵌套对象数组操作全攻略:轻松提取 children 值,掌握复杂数据结构处理

目录
  1. 什么是嵌套对象数组?
  2. 为什么需要处理嵌套对象数组?
  3. 复杂数据结构示例
  4. 提取 children 值的多种方法
  5. 嵌套对象数组的 CRUD 操作
  6. 常见问题与解决方案
  7. 总结

什么是嵌套对象数组?

嵌套对象数组是指一个数组中的元素是对象,而这些对象中又包含数组或对象的结构。例如:

const data = [
  {
    id: 1,
    name: "Parent 1",
    children: [
      { id: 2, name: "Child 1" },
      { id: 3, name: "Child 2" },
    ],
  },
  {
    id: 4,
    name: "Parent 2",
    children: [
      { id: 5, name: "Child 3" },
      { id: 6, name: "Child 4" },
    ],
  },
];

为什么需要处理嵌套对象数组?

  • 数据展示:前端开发中,经常需要将嵌套数据渲染到页面上。
  • 数据处理:需要对嵌套数据进行增删改查(CRUD)操作。
  • 性能优化:避免重复遍历,提高数据处理效率。

复杂数据结构示例

以下是一个更复杂的嵌套对象数组示例:

const complexData = [
  {
    id: 1,
    name: "Root 1",
    children: [
      {
        id: 2,
        name: "Child 1",
        children: [
          { id: 3, name: "Grandchild 1" },
          { id: 4, name: "Grandchild 2" },
        ],
      },
      { id: 5, name: "Child 2" },
    ],
  },
  {
    id: 6,
    name: "Root 2",
    children: [
      { id: 7, name: "Child 3" },
      {
        id: 8,
        name: "Child 4",
        children: [
          { id: 9, name: "Grandchild 3" },
          { id: 10, name: "Grandchild 4" },
        ],
      },
    ],
  },
];

提取 children 值的多种方法

方法 1:递归遍历
function getChildrenValues(data) {
  let result = [];
  data.forEach((item) => {
    if (item.children) {
      result = result.concat(getChildrenValues(item.children));
    }
    result.push(item);
  });
  return result;
}

console.log(getChildrenValues(complexData));
方法 2:使用 flatMap 和递归
function getChildrenValues(data) {
  return data.flatMap((item) => {
    const children = item.children ? getChildrenValues(item.children) : [];
    return [item, ...children];
  });
}

console.log(getChildrenValues(complexData));
方法 3:使用 reduce 和递归
function getChildrenValues(data) {
  return data.reduce((acc, item) => {
    const children = item.children ? getChildrenValues(item.children) : [];
    return [...acc, item, ...children];
  }, []);
}

console.log(getChildrenValues(complexData));
方法 4:使用栈(非递归)
function getChildrenValues(data) {
  const stack = [...data];
  const result = [];
  while (stack.length) {
    const item = stack.pop();
    result.push(item);
    if (item.children) {
      stack.push(...item.children.reverse());
    }
  }
  return result;
}

console.log(getChildrenValues(complexData));

嵌套对象数组的 CRUD 操作

新增数据
function addChild(parentId, newChild, data) {
  return data.map((item) => {
    if (item.id === parentId) {
      return {
        ...item,
        children: item.children ? [...item.children, newChild] : [newChild],
      };
    }
    if (item.children) {
      return {
        ...item,
        children: addChild(parentId, newChild, item.children),
      };
    }
    return item;
  });
}

const newData = addChild(2, { id: 11, name: "New Child" }, complexData);
console.log(newData);
查询数据
function findItemById(id, data) {
  for (const item of data) {
    if (item.id === id) return item;
    if (item.children) {
      const found = findItemById(id, item.children);
      if (found) return found;
    }
  }
  return null;
}

console.log(findItemById(3, complexData));
更新数据
function updateItemById(id, newData, data) {
  return data.map((item) => {
    if (item.id === id) {
      return { ...item, ...newData };
    }
    if (item.children) {
      return {
        ...item,
        children: updateItemById(id, newData, item.children),
      };
    }
    return item;
  });
}

const updatedData = updateItemById(3, { name: "Updated Name" }, complexData);
console.log(updatedData);
删除数据
function deleteItemById(id, data) {
  return data
    .filter((item) => item.id !== id)
    .map((item) => {
      if (item.children) {
        return {
          ...item,
          children: deleteItemById(id, item.children),
        };
      }
      return item;
    });
}

const deletedData = deleteItemById(3, complexData);
console.log(deletedData);

常见问题与解决方案

  1. 递归栈溢出

    • 对于非常深的嵌套结构,递归可能导致栈溢出。可以使用栈(非递归)方法替代。
  2. 性能问题

    • 如果数据量非常大,建议使用非递归方法或优化算法。
  3. 数据格式不一致

    • 确保数据结构一致,避免因格式问题导致错误。

总结

通过本教程,你已经掌握了 JavaScript 中处理嵌套对象数组的多种方法,包括提取 children 值、增删改查操作等。希望这些技巧能帮助你更好地处理复杂数据结构!


为了方便你在浏览器的控制台中直接运行和查看结果,我会将所有案例整理成一个完整的脚本,并添加注释和 console.log 语句,方便你逐步查看输出结果。

以下是整理后的代码:


完整脚本:嵌套对象数组操作案例

// ======================
// 复杂数据结构示例
// ======================
const complexData = [
  {
    id: 1,
    name: "Root 1",
    children: [
      {
        id: 2,
        name: "Child 1",
        children: [
          { id: 3, name: "Grandchild 1" },
          { id: 4, name: "Grandchild 2" },
        ],
      },
      { id: 5, name: "Child 2" },
    ],
  },
  {
    id: 6,
    name: "Root 2",
    children: [
      { id: 7, name: "Child 3" },
      {
        id: 8,
        name: "Child 4",
        children: [
          { id: 9, name: "Grandchild 3" },
          { id: 10, name: "Grandchild 4" },
        ],
      },
    ],
  },
];

console.log("原始数据:", complexData);

// ======================
// 提取 children 值的多种方法
// ======================

// 方法 1:递归遍历
function getChildrenValuesRecursive(data) {
  let result = [];
  data.forEach((item) => {
    if (item.children) {
      result = result.concat(getChildrenValuesRecursive(item.children));
    }
    result.push(item);
  });
  return result;
}

console.log("方法 1(递归遍历)结果:", getChildrenValuesRecursive(complexData));

// 方法 2:使用 `flatMap` 和递归
function getChildrenValuesFlatMap(data) {
  return data.flatMap((item) => {
    const children = item.children ? getChildrenValuesFlatMap(item.children) : [];
    return [item, ...children];
  });
}

console.log("方法 2(flatMap + 递归)结果:", getChildrenValuesFlatMap(complexData));

// 方法 3:使用 `reduce` 和递归
function getChildrenValuesReduce(data) {
  return data.reduce((acc, item) => {
    const children = item.children ? getChildrenValuesReduce(item.children) : [];
    return [...acc, item, ...children];
  }, []);
}

console.log("方法 3(reduce + 递归)结果:", getChildrenValuesReduce(complexData));

// 方法 4:使用栈(非递归)
function getChildrenValuesStack(data) {
  const stack = [...data];
  const result = [];
  while (stack.length) {
    const item = stack.pop();
    result.push(item);
    if (item.children) {
      stack.push(...item.children.reverse());
    }
  }
  return result;
}

console.log("方法 4(栈)结果:", getChildrenValuesStack(complexData));

// ======================
// 嵌套对象数组的 CRUD 操作
// ======================

// 新增数据
function addChild(parentId, newChild, data) {
  return data.map((item) => {
    if (item.id === parentId) {
      return {
        ...item,
        children: item.children ? [...item.children, newChild] : [newChild],
      };
    }
    if (item.children) {
      return {
        ...item,
        children: addChild(parentId, newChild, item.children),
      };
    }
    return item;
  });
}

const newData = addChild(2, { id: 11, name: "New Child" }, complexData);
console.log("新增数据后的结果:", newData);

// 查询数据
function findItemById(id, data) {
  for (const item of data) {
    if (item.id === id) return item;
    if (item.children) {
      const found = findItemById(id, item.children);
      if (found) return found;
    }
  }
  return null;
}

console.log("查询 id=3 的结果:", findItemById(3, complexData));

// 更新数据
function updateItemById(id, newData, data) {
  return data.map((item) => {
    if (item.id === id) {
      return { ...item, ...newData };
    }
    if (item.children) {
      return {
        ...item,
        children: updateItemById(id, newData, item.children),
      };
    }
    return item;
  });
}

const updatedData = updateItemById(3, { name: "Updated Name" }, complexData);
console.log("更新 id=3 后的结果:", updatedData);

// 删除数据
function deleteItemById(id, data) {
  return data
    .filter((item) => item.id !== id)
    .map((item) => {
      if (item.children) {
        return {
          ...item,
          children: deleteItemById(id, item.children),
        };
      }
      return item;
    });
}

const deletedData = deleteItemById(3, complexData);
console.log("删除 id=3 后的结果:", deletedData);

使用方法

  1. 打开浏览器的开发者工具(通常按 F12Ctrl + Shift + I)。
  2. 切换到 Console(控制台)标签。
  3. 将上述代码复制粘贴到控制台中,按 Enter 运行。
  4. 查看控制台输出的结果,逐步分析每个方法的输出。

输出示例

运行后,控制台会输出以下内容:

原始数据: [ {...}, {...} ]
方法 1(递归遍历)结果: [ {...}, {...}, {...} ]
方法 2(flatMap + 递归)结果: [ {...}, {...}, {...} ]
方法 3(reduce + 递归)结果: [ {...}, {...}, {...} ]
方法 4(栈)结果: [ {...}, {...}, {...} ]
新增数据后的结果: [ {...}, {...}, {...} ]
查询 id=3 的结果: { id: 3, name: "Grandchild 1" }
更新 id=3 后的结果: [ {...}, {...}, {...} ]
删除 id=3 后的结果: [ {...}, {...}, {...} ]

在这里插入图片描述
在这里插入图片描述

总结

通过这个脚本,你可以在浏览器的控制台中直接运行所有案例,查看每一步的结果。希望这对你的学习和调试有所帮助!如果有其他问题,欢迎随时提问!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值