我有一个特定的用例,我想将数组中的所有对象合并成一个新数组。所以我在我的网站上有一个表单,用户在预订时添加参与者。他们可以添加任意数量的参与者。我将它们保存为JSON格式并存储在数据库中,现在我想形成所有参与者的数组,以便可以在表格中显示它们。
因此,我首先从特定列表中获取所有交易,得到一个对象数组,然后循环遍历它们,并且仅获取
因此,我的transactions对象看起来像:
因此,我首先从特定列表中获取所有交易,得到一个对象数组,然后循环遍历它们,并且仅获取
transaction.attributes.protectedData.questions
,这个属性包含每个交易的参与者。因此,我的transactions对象看起来像:
[
{
"type":"transaction",
"attributes":{
"createdAt":"2021-06-24T08:50:26.911Z",
"protectedData":{
"questions":[
[
{
"question":"name",
"answer":"Mario North"
},
{
"question":"email",
"answer":"mario@gmail.com"
}
]
],
"ticketType":{
"name":"Main entry",
"quantity":1
}
}
}
},
{
"type":"transaction",
"attributes":{
"createdAt":"2021-06-24T08:48:57.646Z",
"protectedData":{
"questions":[
[
{
"question":"name",
"answer":"John Adkins"
},
{
"question":"email",
"answer":"john@gmail.com"
}
],
[
{
"question":"name",
"answer":"Thomas Smith"
},
{
"question":"email",
"answer":"thomas@gmail.com"
}
]
],
"ticketType":{
"name":"General entry",
"quantity":2
}
}
}
}
]
所以我需要遍历每个交易,然后循环遍历问题和问题数组中的每个新数组是一个新的参与者。在每个参与者中,我需要从交易属性保存createdAt和ticketType值。
所以我的最终数组/对象应该像这样:
[
{
"createdAt":"2021-06-24T08:50:26.911Z",
"ticketType":"Main entry",
"name":"Mario North",
"email":"mario@gmail.com"
},
{
"createdAt":"2021-06-24T08:48:57.646Z",
"ticketType":"General entry",
"name":"John Adkins",
"email":"john@gmail.com"
},
{
"createdAt":"2021-06-24T08:48:57.646Z",
"ticketType":"General entry",
"name":"Thomas Smith",
"email":"thomas@gmail.com"
}
]
我可以获取参与者列表,并为每个参与者添加createdAt和ticketType。但我不知道如何使我的问题/答案出现在我所发布的期望对象中。这是我的代码:
export const denormalisedParticipantList = transactions => {
let participants = [];
transactions.map(transaction => {
const createdAt = transaction.attributes.createdAt;
const questions = transaction.attributes.protectedData?.questions;
const ticketType = transaction.attributes.protectedData?.ticketType?.name;
return questions.map(q => {
// Form new participant object
const participant = {
createdAt,
ticketType,
...Object.fromEntries(q.map(({ question, answer }) => [question, answer])),
};
// Push new participant
participants.push(participant);
});
});
return participants;
};
自从昨晚开始我一直在尝试弄清楚它,但我无法使它工作。请问有人能帮助我弄清楚如何从我的交易对象中制作最终数组吗?我会非常感激。