规范化转换模式问题



我如何转换一些 json 数组

[
{
"travelExpenseId":11,
"tripId":2,
"paymentPurpose":"some payment purpose 2",
"receiptNumber":"EF12312_2",
"receiptDate":"2018-09-30T00:00:00",
"receiptPrice":107000.0,
"receiptCurrency":"руб."
},
{
"travelExpenseId":10,
"tripId":2,
"paymentPurpose":"some payment purpose 1",
"receiptNumber":"EF12312_1",
"receiptDate":"2018-09-30T00:00:00",
"receiptPrice":107000.0,
"receiptCurrency":"руб."
}
]

到适合通过travelExpenseId快速获取费用并通过tripId获取费用的东西。

现在我使用这样的东西:

export const expenseSchema = new schema.Entity('expenses', {}, { idAttribute: 'travelExpenseId' });
export const expensesListSchema = [expenseSchema];

并得到结果:

data: {
entities: {
expenses: {
'10': {
travelExpenseId: 10,
tripId: 2,
paymentPurpose: 'some payment purpose 1',
receiptNumber: 'EF12312_1',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
},
'11': {
travelExpenseId: 11,
tripId: 2,
paymentPurpose: 'some payment purpose 2',
receiptNumber: 'EF12312_2',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
}
}
},
result: [
11,
10
]
}

我想向 data.entities 添加其他架构expensesByTripId,因此结果应如下所示:

data: {
entities: {
expensesByTripId: {
'2': [10, 11],
},
expenses: {
'10': {
travelExpenseId: 10,
tripId: 2,
paymentPurpose: 'some payment purpose 1',
receiptNumber: 'EF12312_1',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
},
'11': {
travelExpenseId: 11,
tripId: 2,
paymentPurpose: 'some payment purpose 2',
receiptNumber: 'EF12312_2',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
}
}
},
result: [
11,
10
]
}

或者请为我提供适合我的情况的任何其他方式

let data = {
entities: {
expenses: {
'10': {
travelExpenseId: 10,
tripId: 2,
paymentPurpose: 'some payment purpose 1',
receiptNumber: 'EF12312_1',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
},
'11': {
travelExpenseId: 11,
tripId: 2,
paymentPurpose: 'some payment purpose 2',
receiptNumber: 'EF12312_2',
receiptDate: '2018-09-30T00:00:00',
receiptPrice: 107000,
receiptCurrency: 'руб.'
}
}
},
result: [
11,
10
]
}
let object = {};
Object.values(data.entities.expenses).forEach(expenses => {

let result = object[expenses.tripId] || [];
object[expenses.tripId] = [...result, expenses.travelExpenseId];
});
		data.entities["expensesByTripId"] = object;
console.log(data);

我不确定Normalizr是如何工作的,但我正在使用 VanillaJS 根据您的要求定制一个

相关内容

  • 没有找到相关文章

最新更新