let raw = {
primaryKey: {
v: 3142
},
caseNumber: 0,
caseType: {
v: 21,
d: 'HSE incident - Near miss'
},
fields: {
Location: {
values: [
{
v: 553,
d: 'Northern Europe - Norway - Adm. building Norway'
}
]
},
CaseDate: {
values: [
{
v: '2017-01-26T15:44:46'
}
]
},
Title: {
values: [{}]
},
Description: {
values: [{}]
},
},
subTables: {
TblLossPotEvaluation: [
{
primaryKey: {
v: 1
},
subTables: {
TblFooBar: [{primaryKey:{v:666}, fields: { Dust: {values: [{v:999}] } }}]
},
fields: {
PotRiskEvRecurrence: {
values: [
{
v: 0
}
]
},
PotRiskEvLossPotentialRevNo: {
values: [
{
v: 1
}
]
},
PotRiskEvRecurrenceFactor: {
values: [{}]
}
}
},
{
primaryKey: {
v: 2
},
subTables: {
TblFooBar: [{primaryKey:{v:777}, fields: { Dust: {values: [{v:888}] } }}]
},
fields: {
PotRiskEvRecurrence: {
values: [
{
v: 8
}
]
},
PotRiskEvLossPotentialRevNo: {
values: [
{
v: 8
}
]
},
PotRiskEvRecurrenceFactor: {
values: [{}]
}
}
}
]
}
};
const preProcessTableRows = (table, tableName, parentPk, parent, root) => {
// manual normalizr
root.entities[tableName] = root.entities[tableName] || []
// for reference ids
parent[tableName] = parent[tableName] || []
table.forEach( row => {
// create uniuqe id from legacy combined keys
row.id = { ...parentPk, ... { [tableName] : row.primaryKey.v} }
const tablesForThisRow = Object.keys(row.subTables || {})
tablesForThisRow.forEach( subTableName => preProcessTableRows( row.subTables[subTableName], subTableName, row.id, row, root ))
// id must be string for referencing, and as key for collections
const rowId = JSON.stringify(row.id)
// add this row id to parent as reference
parent[tableName].push(rowId)
// delete noise
delete row.subTables
const finalRow = { ...row, ...row.fields, ...{id: row.id} }
root.entities[tableName][rowId] = finalRow
//root.byId[rowId] = finalRow
})
}
const entitiesFound = {};
const process = (org) => {
// shallow copy
const doc = {...org}
//
const docid = JSON.stringify(doc.primaryKey.v)
doc.byId = {}
doc.entities = {}
doc.entities.TblTrans = {[docid] : {...doc, ...doc.fields} }
doc.byId[docid] = {...doc, ...doc.fields}
// recusively flatten each item in subTable, after assigning parent primaryKey.v
Object.keys(doc.subTables)
.forEach(
table => preProcessTableRows( doc.subTables[table], table, {TblTrans: doc.primaryKey.v}, /*doc.entities.TblTrans[docid]*/ doc, doc) )
return doc;
};
// normalizer needs to know the name of keys beforehand, no go
//const schema = {};
console.log( process(raw) )