javascript - 如何更改对象数组中所有出现的对象键
问题描述
我有这个样本数据:
const data = [
{
id: 1,
title: 'Sports',
menus: [
{
id: 2,
title: 'Basketball',
menus: [
{
id: 3,
title: 'NBA',
},
{
id: 4,
title: 'NCAA',
},
{
id: 5,
title: 'G-League',
},
],
},
],
},
{
id: 100,
title: 'Names',
menus: [],
},
];
我想将所有menus
键更改为children
,因此结果将是:
const result = [
{
id: 1,
title: 'Sports',
children: [
{
id: 2,
title: 'Basketball',
children: [
{
id: 3,
title: 'NBA',
},
{
id: 4,
title: 'NCAA',
},
{
id: 5,
title: 'G-League',
},
],
},
],
},
{
id: 100,
title: 'Names',
children: [],
},
];
我正在尝试使用此代码:
const replacer = { menus: 'children' };
const transform = useCallback(
(obj) => {
if (obj && Object.getPrototypeOf(obj) === Object.prototype) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [replacer[k] || k, transform(v)]));
}
return obj;
},
[replacer]
);
但它只更改第一级的键。我怎样才能让它工作?
解决方案
您可以使用利用解构的递归函数:
const replaceKey = arr =>
arr.map(({menus, ...o}) =>
menus ? {...o, children: replaceKey(menus)} : o);
const data = [{id: 1,title: 'Sports',menus: [{id: 2,title: 'Basketball',menus: [{id: 3,title: 'NBA',},{id: 4,title: 'NCAA',},{id: 5,title: 'G-League',},],},],},{id: 100,title: 'Names',menus: [],},];
console.log(replaceKey(data));
要动态提供旧/新密钥,请使用以下变体:
const replaceKey = (arr, source, target) =>
arr.map(({[source]: v, ...o}) =>
v ? {...o, [target]: replaceKey(v, source, target)} : o);
const data = [{id: 1,title: 'Sports',menus: [{id: 2,title: 'Basketball',menus: [{id: 3,title: 'NBA',},{id: 4,title: 'NCAA',},{id: 5,title: 'G-League',},],},],},{id: 100,title: 'Names',menus: [],},];
console.log(replaceKey(data, "menus", "children"));
此代码假定给定键的值是数组。如果由于某种原因它们的值可能是别的东西,那么代码需要更多的扩展:
const data = [{id: 1,title: 'Sports',menus: [{id: 2,title: 'Basketball',menus: [{id: 3,title: 'NBA',},{id: 4,title: 'NCAA',},{id: 5,title: 'G-League',},],},],},{id: 100,title: 'Names',menus: 13,},];
const replaceKey = (arr, source, target) =>
Array.isArray(arr) ? arr.map(({[source]: value, ...o}) =>
value !== undefined ? {...o, [target]: replaceKey(value, source, target)} : o
) : arr;
console.log(replaceKey(data, "menus", "children"));
要查看此代码的效果,最后一个menus
键的值已更改为 13。
推荐阅读
- javascript - 您如何使用 Neptune 在本地进行测试?
- javascript - Javascript 中数组与对象的实例化。数组什么时候是对象,什么时候得到数组的方法?
- c++ - Mutex 不是 cv 的成员,用 g++ 编译失败
- python - 插入数据库时出现无效语法 ON CONFLICT
- sql - postgresql如何结合这两个查询?
- c# - 为什么我的 .NET 字符串在内存中这么大?
- jquery - 尝试将键传递给自定义函数的参数以显示数据中的所有值
- ffmpeg - 我怎么知道某个文件是视频文件?
- javascript - 如何制作具有 3 种颜色和大量曲线的多渐变背景?
- apache-spark - SparkUI 在独立模式下运行时不显示选项卡(作业、阶段、存储、环境……)