Open openks opened 6 years ago
本地测试代码如下 直接在vscode里run code即可
var { normalize, schema, denormalize } = require('normalizr'); const underwrite = new schema.Entity( 'underWrites', {}, { idAttribute: value => value.id, }, ); const ivProduct = new schema.Entity( 'ivProducts', {}, { idAttribute: value => value.productId, }, ); const mainTask = new schema.Entity( 'mainTasks', { ivProducts: [ivProduct], underwrite: underwrite, }, { idAttribute: value => value.mainTaskId, }, ); var originalData = ''; var normalizedData = ''; console.log(originalData, normalizedData); originalData = [ { mainTaskId: 100015570, name: '测试', idType: '01', idNum: '2114021XXXXXXXX12', ivProducts: [ { productId: 106255, productName: 'test1', productCode: '23', }, ], underwrite: { id: 125254, mainTaskId: 100015570, }, }, { mainTaskId: 100015560, name: '高老庄', idType: '01', idNum: '211402199XXXXXXX12', ivProducts: [ { productId: 107170, productName: 'test2', productCode: '26', }, { productId: 105382, productName: 'test4', productCode: '24', }, { productId: 105383, productName: 'test3', productCode: '25', }, ], underwrite: { id: 125199, mainTaskId: 100015560, }, }, { mainTaskId: 100015540, name: '测试666', idType: '01', idNum: '211XXXXXXX012', ivProducts: [ { productId: 100382, productName: 'test4', productCode: '24', }, { productId: 100383, productName: 'test3', productCode: '25', }, { productId: 100170, productName: 'test2', productCode: '26', }, ], underwrite: { id: 124179, mainTaskId: 100015540, }, }, ]; normalizedData = normalize(originalData, [mainTask]); console.log(JSON.stringify(normalizedData));
其中处理后的normalizedData数据如下
normalizedData
{ "entities": { "ivProducts": { "105382": { "productId": 105382, "productName": "test4", "productCode": "24" }, "105383": { "productId": 105383, "productName": "test3", "productCode": "25" }, "106655": { "productId": 106655, "productName": "test1", "productCode": "23" }, "107170": { "productId": 107170, "productName": "test2", "productCode": "26" } }, "underWrites": { "124179": { "id": 124179, "mainTaskId": 100015540 }, "125199": { "id": 125199, "mainTaskId": 100015560 }, "125254": { "id": 125254, "mainTaskId": 100015570 } }, "mainTasks": { "100015540": { "mainTaskId": 100015540, "name": "测试666", "idType": "01", "idNum": "211XXXXXXX012", "ivProducts": [105382, 105383, 107170], "underwrite": 124179 }, "100015560": { "mainTaskId": 100015560, "name": "高老庄", "idType": "01", "idNum": "211402199XXXXXXX12", "ivProducts": [107170, 105382, 105383], "underwrite": 125199 }, "100015570": { "mainTaskId": 100015570, "name": "测试", "idType": "01", "idNum": "2114021XXXXXXXX12", "ivProducts": [106655], "underwrite": 125254 } } }, "result": [100015570, 100015560, 100015540] }
还原为原始数据(文档看了很久没懂,一点一点试出来的,囧)
var denormalizedData = denormalize( normalizedData.result, [mainTask], normalizedData.entities, ); console.log('denormalizedData', JSON.stringify(denormalizedData)); // 正常解析为原数组
本地测试代码如下 直接在vscode里run code即可
其中处理后的
normalizedData
数据如下还原为原始数据(文档看了很久没懂,一点一点试出来的,囧)