在不影响第一个订单的情况下,覆盖另一个对象数组

时间:2018-03-02 09:58:58

标签: javascript ecmascript-6 lodash

我有两个对象数组如下:

var listA = [
    { name: 'monday', reported: '', closed: '' },
    { name: 'tuesday', reported: '', closed: '' },
    { name: 'wednesday', reported: '', closed: '' },
    { name: 'thursday', reported: '', closed: '' },
    { name: 'friday', reported: '', closed: '' },
    { name: 'saturday', reported: '', closed: '' },
    { name: 'sunday', reported: '', closed: '' }
];

var listB = [
    { name: 'friday', reported: '23', closed: '17' },
    { name: 'tuesday', reported: '28', closed: '24' },
    { name: 'saturday', reported: '10', closed: '8' },
];

我想用listB中的值覆盖listA而不影响listA中对象的顺序。我用_.unionBy JSFiddle试了一下。结果如下:

{name: "friday", reported: "23", closed: "17"}
{name: "tuesday", reported: "28", closed: "24"}
{name: "saturday", reported: "10", closed: "8"}
{name: "monday", reported: "", closed: ""}
{name: "wednesday", reported: "", closed: ""}
{name: "thursday", reported: "", closed: ""}
{name: "sunday", reported: "", closed: ""}

我期待以下结果:

{name: "monday", reported: "", closed: ""}
{name: "tuesday", reported: "28", closed: "24"}
{name: "wednesday", reported: "", closed: ""}
{name: "thursday", reported: "", closed: ""}
{name: "friday", reported: "23", closed: "17"}
{name: "saturday", reported: "10", closed: "8"}
{name: "sunday", reported: "", closed: ""}

我知道如何通过迭代listA并将listB中的值替换为name来实现。但是想知道是否有更好的方法通过lodash或ES6做到这一点。

1 个答案:

答案 0 :(得分:2)

使用map(以便不必更改数组)和find

var listC = listA.map( s => 
     Object.assign( {}, s, 
      listB.find( s1 => s1.name == s.name ) ) );

<强>演示

var listA = [
    { name: 'monday', reported: '', closed: '' },
    { name: 'tuesday', reported: '', closed: '' },
    { name: 'wednesday', reported: '', closed: '' },
    { name: 'thursday', reported: '', closed: '' },
    { name: 'friday', reported: '', closed: '' },
    { name: 'saturday', reported: '', closed: '' },
    { name: 'sunday', reported: '', closed: '' }
];

var listB = [
    { name: 'friday', reported: '23', closed: '17' },
    { name: 'tuesday', reported: '28', closed: '24' },
    { name: 'saturday', reported: '10', closed: '8' },
];

var listC = listA.map( s => 
     Object.assign( {}, s, 
      listB.find( s1 => s1.name == s.name ) ) );

console.log( listC );