使用动态键递归创建嵌套对象

问题描述 投票:1回答:1

我对递归感到满意,但是遇到了需要使用可变键创建嵌套对象的情况。已经看到了使用“ b.c”之类的命名空间约定的其他建议,以弄清楚在何处深度分配值(请参见下面的期望输出),但是实现起来很困难。该结构可以无限嵌套。

// 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

javascript object recursion
1个回答
0
投票

嵌套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));
© www.soinside.com 2019 - 2024. All rights reserved.