我有两个对象数组如下:
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做到这一点。
答案 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 );