首页 > 解决方案 > 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'
}]

有人有任何提示吗?

标签: javascriptjoinmerge

解决方案


const newOrderList = orders.map((order, index) => {
   let payedOrder = ordersPayed.find(o => o.orderId === order.orderId);
   return Object.assign({}, order, payedOrder)
});

推荐阅读