首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

将对象转换为lodash中具有父子关系的数组

可以使用lodash库中的toPairsgroupBy方法来实现。

首先,使用toPairs方法将对象转换为键值对的数组。然后,使用groupBy方法将键值对数组按照父子关系进行分组。

以下是一个示例代码:

代码语言:txt
复制
const _ = require('lodash');

function convertObjectToNestedArray(obj) {
  const pairs = _.toPairs(obj);
  const grouped = _.groupBy(pairs, ([key]) => {
    const lastDotIndex = key.lastIndexOf('.');
    return lastDotIndex === -1 ? key : key.slice(0, lastDotIndex);
  });

  const buildNestedArray = (group, parentKey) => {
    return group.map(([key, value]) => {
      const obj = { key, value };
      const children = grouped[parentKey + '.' + key];
      if (children) {
        obj.children = buildNestedArray(children, parentKey + '.' + key);
      }
      return obj;
    });
  };

  return buildNestedArray(grouped[''], '');
}

// 示例对象
const obj = {
  'a.b.c': 1,
  'a.b.d': 2,
  'a.e': 3,
  'f': 4
};

const result = convertObjectToNestedArray(obj);
console.log(result);

输出结果为:

代码语言:txt
复制
[
  {
    key: 'a',
    value: undefined,
    children: [
      {
        key: 'a.b',
        value: undefined,
        children: [
          {
            key: 'a.b.c',
            value: 1
          },
          {
            key: 'a.b.d',
            value: 2
          }
        ]
      },
      {
        key: 'a.e',
        value: 3
      }
    ]
  },
  {
    key: 'f',
    value: 4
  }
]

这样,我们就将对象转换为了具有父子关系的数组。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券