I am trying to transform the data from 2 endpoints to mock up a basic table UI, but currently have no access to the db. I have played about with lodash and have had a little success with being able to get the two arrays merged based on references using _.defaults etc but with no success.
I am trying to display the data in a flat table by Row Id, with the newly inserted keys being used as column references
BusData1 = [
{
id: 1,
ObjRef: 1,
ObjRefLabel: "ObjRef1 - Option 1",
ObjRefDesc: "Option 1 Desc",
parentId: null,
},
{
id: 12,
ObjRef: 1,
ObjRefLabel: "ObjRef1 - Option 2",
ObjRefDesc: "Option 2 Desc",
parentId: null,
},
];
OtherData2 = [
{
id: 21,
BusDataId: 1,
ObjRef: 1,
ObjRefDesc: "Desc",
},
{
id: 22,
BusDataId: 1,
ObjRef: 0,
ObjRefDesc: "Desc",
},
{
id: 31,
BusDataId: 1,
ObjRef: 1,
ObjRefDesc: "Desc",
},
{
id: 32,
BusDataId: 12,
ObjRef: 0,
ObjRefDesc: "Desc",
},
];
I am trying to merge array 2 into array 1 with the key values, but on insert into array 1 I am trying to update the key to include the object id so each insert key has a unique reference.
Combined = [
{
id: 1,
ObjRef: 1,
BusDataId21ObjRef: 1,
BusDataId22ObjRef: 0,
BusDataId31ObjRef: 1,
ObjRefLabel: "Option 1",
ObjRefDesc: "Desc",
parentId: null,
},
{
id: 12,
ObjRef: 1,
BusDataId31ObjRef: 0,
ObjRefLabel: "Option 2",
ObjRefDesc: "Desc",
parentId: null,
},
];
So far i have gotten the below from another StackOverflow post, but I cannot get beyond this.
const combine = _.map(otherData2, function(row){
return _.defaults(row, _.find(otherData2, {BusDataID: row.id}
Any advice or guidance here would be appreciated
CodePudding user response:
A simple approach
Loop through the business data array. For each business data item, find the elements in the second array that belong to it, and insert them as extra entries.
BusData1 = [{
id: 1,
ObjRef: 1,
ObjRefLabel: "ObjRef1 - Option 1",
ObjRefDesc: "Option 1 Desc",
parentId: null,
},
{
id: 12,
ObjRef: 1,
ObjRefLabel: "ObjRef1 - Option 2",
ObjRefDesc: "Option 2 Desc",
parentId: null,
},
];
OtherData2 = [{
id: 21,
BusDataId: 1,
ObjRef: 1,
ObjRefDesc: "Desc",
},
{
id: 22,
BusDataId: 1,
ObjRef: 0,
ObjRefDesc: "Desc",
},
{
id: 31,
BusDataId: 1,
ObjRef: 1,
ObjRefDesc: "Desc",
},
{
id: 32,
BusDataId: 12,
ObjRef: 0,
ObjRefDesc: "Desc",
},
];
BusData1.forEach(business => {
OtherData2.filter(
other => other.BusDataId == business.id
).forEach(
other => {
business["BusDataId" other.id "ObjRef"] = other.ObjRef
})
})
console.log(BusData1)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Optimization
This is O(n x m). If that is not fast enough for enormous arrays, you could take advantage of known properties?
For example, if the items in the second array are ordered such that any entries that belong to BusData1 element 1 appear before those that belong to BusData1 element 2, you could do it with a single pass, i.e. O(n m).