What is the best way to join data in JavaScript? Are there libraries like e.g. Pandas
in Python
or is iteration the way to go? I have two arrays with different objects inside. The list orders
contains information about orders in general and the list ordersPayed
contains the information whether an order was already payed + the amount etc.
const orders = [
{
orderId: 1,
orderDate: '2018-01-01',
orderAmount: 100
},
{
orderId: 2,
orderDate: '2018-02-01',
orderAmount: 100
},
{
orderId: 3,
orderDate: '2018-03-01',
orderAmount: 100
},
{
orderId: 4,
orderDate: '2018-03-01',
orderAmount: 100
}];
const ordersPayed = [
{
orderId: 1,
payedAmount: 90,
debitorName: 'abc'
},
{
orderId: 3,
payedAmount: 80,
debitorName: 'abc'
},
{
orderId: 6,
payedAmount: 90,
debitorName: 'abc'
}];
let newOrderList = [];
for (i = 0; i < orders.length; i++) {
for (j = 0; j < ordersPayed.length; j++) {
if (orders[i].orderId == ordersPayed[j].orderId) {
newOrderList.push(orders[i].orderId);
newOrderList.push(orders[i].orderDate);
newOrderList.push(orders[i].orderAmount);
newOrderList.push(ordersPayed[j].payedAmount);
newOrderList.push(ordersPayed[j].debitorName);
}
else if (j == (ordersPayed.length-1)) {
newOrderList.push(orders[i].orderId);
newOrderList.push(orders[i].orderDate);
newOrderList.push(orders[i].orderAmount);
newOrderList.push('not_payed_yet');
newOrderList.push('not_known_yet');
}
}
}
console.log(newOrderList);
The matching is done by the key orderId
. At the end I want to have a new list with all orders + the corresponding info whether they were already payed or not.
The code above is my approach to go, but I don't know if this is good for performance reasons and whether there are more pitfalls. So I thought of a matching library or something similar.
Unfortunately this doesn't work 100% correctly. The result should look something like this:
[{
orderId: 1,
orderDate: '2018-01-01',
orderAmount: 100,
payedAmount: 90
},
{
orderId: 2,
orderDate: '2018-02-01',
orderAmount: 100,
payedAmount: 'not_payed_yet'
},
{
orderId: 3,
orderDate: '2018-03-01',
orderAmount: 100,
payedAmount: 80
},
{
orderId: 4,
orderDate: '2018-03-01',
orderAmount: 100,
payedAmount: 'not_payed_yet'
}]
Anybody got any tips?