【问题标题】:How to change all occurrences of an object key in an array of objects如何更改对象数组中所有出现的对象键
【发布时间】:2021-03-03 11:52:53
【问题描述】:

我有这个样本数据:

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

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

【问题讨论】:

    标签: javascript typescript ecmascript-6


    【解决方案1】:

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

    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。

    【讨论】:

      【解决方案2】:

      如果对象不大:

      let 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:[],},];
      
      data = JSON.parse(JSON.stringify(data).replace(/"menus"\:/g,'"children":'))
      console.log(data)

      【讨论】:

      • 不可能,因为对象会很大。
      【解决方案3】:

      检查这个包:paix
      这需要原始源对象和所需的键替换,然后返回一个带有所需键的新对象,例如:

      npm i paix
      
      import { paix } from 'paix';
      
      const data = [
        {
          id: 1,
          title: 'Sports',
          menus: [
            {
              id: 2,
              title: 'Basketball',
              menus: [
                {
                  id: 3,
                  title: 'NBA',
                },
              ],
            },
          ],
        },
        {
          id: 100,
          title: 'Names',
          menus: [],
        },
      ];
                         
      const keys_swap = {menus: "children"};
      const result = data.map(i => paix(i, keys_swap));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2021-12-29
        • 2021-05-20
        • 2020-12-15
        • 2021-02-12
        • 2011-10-12
        相关资源
        最近更新 更多