带有Redux的Normalizr,带有嵌套的对象数组



我刚开始在Redux中使用normalizer,但我无法使其工作尽管我可以用简单的JavaScript来完成

我有一组对象

const data = [
{
data_detail: [
{
category: 'newCategory',
_id: '123',
},
],
_id: 'abc_id',
customer: {
_id: '456',
email: 'hello@gmail.com',
name: 'Bob',
},
date: '2021-01-10T01:51:24.387Z',
},
];

我需要把它转换成

const normalizedResponse = {
customers: {
'456': {
_id: '456',
email: 'hello@gmail.com',
name: 'Bob',
},
},
details: {
'123': {
category: 'newCategory',
_id: '123',
},
},
orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},
};

步骤1:只显示orders

我的工作:

const userSchema = new schema.Entity(
'orders',
);
const userListSchema = new schema.Array(userSchema);

const normalizedData = normalize(data, userListSchema);

我得到的

{
"entities": {
"orders": {
"abc_id": {
"data_detail": [
{
"category": "newCategory",
"id": "123"
}
],
"id": "abc_id",
"customer": {
"id": "456",
"email": "hello@gmail.com",
"name": "Bob"
},
"date": "2021-01-10T01:51:24.387Z"
},
"abc_id-02": {
"data_detail": [
{
"category": "newCategory1",
"id": "123-02"
}
],
"id": "abc_id-02",
"customer": {
"id": "456-02",
"email": "hello@gmail.com",
"name": "Bob"
},
"date": "2001-01-10T01:51:24.387Z"
}
}
},
"result": [
"abc_id",
"abc_id-02"
]
}

我想得到的:

orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},

问题:如何从订单中删除一些字段并添加新字段?

data对象中有3种不同的实体类型。首先为他们每个人起草一份schema

const detail = new schema.Entity('details');
const customer = new schema.Entity('customers');
const order = new schema.Entity('orders');

然后回去填补关系。看起来order是最外层的实体。CCD_ 5包含details/categories的阵列和单个customer

const order = new schema.Entity('orders', {
data_detail: [detail],
customer,
});

所有实体都使用_id而不是id,因此需要设置idAttribute

您的dataorder中的array。您可以使用new schema.Array(order),但也可以只使用[order]

这是您的最终代码:

const customer = new schema.Entity("customers", {}, { idAttribute: "_id" });
const detail = new schema.Entity("details", {}, { idAttribute: "_id" });
const order = new schema.Entity(
"orders",
{
data_detail: [detail],
customer
},
{ idAttribute: "_id" }
);
const normalizedData = normalize(data, [order]);

这给了你:

{
"entities": {
"details": { 
"123": { 
"category": "newCategory", 
"_id": "123" 
} 
},
"customers": {
"456": { 
"_id": "456", 
"email": "hello@gmail.com", 
"name": "Bob"
}
},
"orders": {
"abc_id": {
"data_detail": ["123"],
"_id": "abc_id",
"customer": "456",
"date": "2021-01-10T01:51:24.387Z"
}
}
},
"result": ["abc_id"]
}

相关内容

  • 没有找到相关文章

最新更新