javascript - JS:如何通过某个键/属性合并/连接对象数组?
问题描述
在 JavaScript 中加入数据的最佳方式是什么?是否有像 eg 这样Pandas
的库Python
或者迭代是要走的路?我有两个数组,里面有不同的对象。该列表orders
包含有关订单的一般信息,该列表ordersPayed
包含订单是否已支付的信息 + 金额等。
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);
匹配由 key 完成orderId
。最后,我想要一个包含所有订单的新列表 + 是否已经付款的相应信息。
上面的代码是我的方法,但我不知道这是否有利于性能以及是否有更多的陷阱。所以我想到了一个匹配的库或类似的东西。
不幸的是,这不能 100% 正确工作。结果应如下所示:
[{
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'
}]
有人有任何提示吗?
解决方案
const newOrderList = orders.map((order, index) => {
let payedOrder = ordersPayed.find(o => o.orderId === order.orderId);
return Object.assign({}, order, payedOrder)
});
推荐阅读
- python - 将csv中的字符串解析为字典
- javascript - TamperMonkey 可以创建书签吗?
- google-cloud-run - 如何在 Google Cloud Run 上运行 WordPress?
- python - numpy总和比字符串计数慢
- .htaccess - .htaccess RewriteRule 文件在另一个文件夹中
- jquery - 是否可以获取子编号并在另一个元素上使用相同的编号?
- java - 使用 CYMK 值绘制图像
- wpf - WPF 和微服务之间的通信
- c# - 使循环中的第一次迭代与其他迭代的速度相同
- python - 如何使用从现有列中提取的数据创建新的 DataFrame 列