javascript - 使用递归转换对象数据

标签 javascript recursion transform

我尝试用递归来转换数据,但我不能,我是递归的新手,请帮助我

它是否需要与递归有关,或者不是你想的那样, 请帮助我

(抱歉我的英语)

这是我的数据

const mock = [
  { $: { id: '001' } },
  {
    $: { id: '002' },
    question: [{
      $: { id: 'r001' },
      prompt: 'some-r001',
      choices: [{
        question: [
          {
            $: { id: 'r001-1' },
            prompt: 'some-r001-1',
            choices: [{
              question: [{
                $: { id: 'r001-1-1' },
                prompt: 'some-r001-1-1',
                choices: [""],
              }]
            }]
          },
          {
            $: { id: 'r001-2' },
            prompt: 'some-r001-2',
            choices: [""],
          },
        ]
      }]
    }]
  }
]

我想转型成这样

const result = {
   'r001': {
     prompt: 'some-r001',
     next: ['r001-1', 'r001-2'],
   },
   'r001-1': {
     prompt: 'some-r001-1',
     next: ['r001-1-1'],
   }
   'r001-1-1': {
     prompt: 'some-r001-1-1',
     next: [],
   },
   'r001-2': {
     prompt: 'some-r001-2',
     next: [],
   },
}

最佳答案

您可以通过迭代调用函数并获取各个部分来展平对象中的数组。

const
    getFlat = (array, parent = []) => array.reduce((r, { question, choices, prompt, $: { id } = {} }) => {
        if (question) return { ...r, ...getFlat(question, parent) };
        if (choices) {
            parent.push(id);
            var next = [];
            return { ...r, [id]: { prompt, next }, ...getFlat(choices, next) };
        }
        return r;
    }, {}),
    mock = [{ $: { id: '001' } }, { $: { id: '002' }, question: [{ $: { id: 'r001' }, prompt: 'some-r001', choices: [{ question: [{ $: { id: 'r001-1' }, prompt: 'some-r001-1', choices: [{ question: [{ $: { id: 'r001-1-1' }, prompt: 'some-r001-1-1', choices: [""] }] }] }, { $: { id: 'r001-2' }, prompt: 'some-r001-2', choices: [""] }] }] }] }],
    result = getFlat(mock);


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 使用递归转换对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848701/

相关文章:

javascript - 获取值字符串表示的不同结果

python - 使用匿名lambda实现阶乘函数的python代码的解释是什么

css - css3中的拟合元素

java - XSLT 复制节点不起作用

Python:查找列表中最大数字的递归函数

html - CSS 过渡和透视在 chrome/ie 和 firefox 中没有给出相同的结果

javascript - 单击图像时如何添加图像

javascript - 如何将innerHTML添加到打印页面

javascript - 上一页 推荐到我的网站

javascript - 将代码重构为尾递归