首页 > 解决方案 > 如何更改对象数组中所有出现的对象键

问题描述

我有这个样本数据:

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]
  );

但它只更改第一级的键。我怎样才能让它工作?

标签: javascripttypescriptecmascript-6

解决方案


您可以使用利用解构的递归函数:

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。


推荐阅读