首页 > 解决方案 > 使用动态键递归创建嵌套对象

问题描述

我对递归很满意,但遇到了需要使用变量键创建嵌套对象的情况。已经看到其他建议使用诸如“bc”之类的命名空间约定来确定在何处深度分配值(请参阅下面的所需输出),但在实施时遇到困难。该结构可以无限嵌套。

// Source
const input = {
  a: {
    type: 'string',
    ex: '1'
  },
  b: {
    type: 'object',
    another: {
      c: {
        type: 'string',
        ex: '2'
      }
    }
  }
}

// Desired
const output = {
  a: '1',
  b: {
    c: '2'
  }
}

// The attempt
function traverse(data, master = {}) {
  Object.entries(data).reduce((collection, [key, value]) => {
    switch (value.type) {
      case 'string':
        collection[key] = value.ex;
        break;
      default:
        collection[key] = traverse(value.another, collection);
    }
    return collection;
  }, master);
}

运行此返回undefined

标签: javascriptobjectrecursion

解决方案


嵌套traverse应该得到一个全新的对象作为第二个参数,你还需要从你的函数中返回一个结果,试试:

// Source
const input = {
  a: {
    type: 'string',
    ex: '1'
  },
  b: {
    type: 'object',
    another: {
      c: {
        type: 'string',
        ex: '2'
      }
    }
  }
}


// The attempt
function traverse(data, master = {}) {
  return Object.entries(data).reduce((collection, [key, value]) => {
    switch (value.type) {
      case 'string':
        collection[key] = value.ex;
        break;
      default:
        collection[key] = traverse(value.another, {});
    }
    return collection;
  }, master);
}

console.log(traverse(input));


推荐阅读