Transform object data with recursive

删除回忆录丶 提交于 2020-02-05 06:00:40

问题


I try to transform data with recursive but I can't, I'm very newbie for recursive please help me

Is it need to do with recursive or not what you guy think, Please help me

(sorry for my english)

This is my data

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: [""],
          },
        ]
      }]
    }]
  }
]

I want to transform to this

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: [],
   },
}

回答1:


You could flat the array in an object by iterating and getting the parts by a recursive call of the function.

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; }


来源:https://stackoverflow.com/questions/59848701/transform-object-data-with-recursive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!