gpt4 book ai didi

javascript - Normalizr 转换模式的麻烦

转载 作者:行者123 更新时间:2023-11-30 20:29:19 24 4
gpt4 key购买 nike

我如何转换一些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 根据您的要求定制一个

关于javascript - Normalizr 转换模式的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com