问题
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