zec*_*ude 5 javascript arrays lodash
我试图不使用unionBylodash 的方法合并对象的两个数组。
目前,我有以下代码可以正常工作:
var array1 = [
{ a: 1, b: 'first'},
{ a: 2, b: 'second'}
];
var array2 = [
{ a: 3, b: 'third'},
{ a: 1, b: 'fourth'}
];
var array3 = __.unionBy(array2, array1, 'a');
Run Code Online (Sandbox Code Playgroud)
输出:
[
{
"a": 3,
"b": "third"
},
{
"a": 1,
"b": "fourth"
},
{
"a": 2,
"b": "second"
}
]
Run Code Online (Sandbox Code Playgroud)
这是理想的结果,但是我不能unionBy在当前的工作环境中使用,因此我正在寻找使用本机JS或其他3.6.0或更低版本的lodash方法的结果。
连接并使用Array#filter和一个辅助对象来删除重复项:
var array1 = [{"a":1,"b":"first"},{"a":2,"b":"second"}];
var array2 = [{"a":3,"b":"third"},{"a":1,"b":"fourth"}];
var result = array2.concat(array1).filter(function(o) {
return this[o.a] ? false : this[o.a] = true;
}, {});
console.log(result);Run Code Online (Sandbox Code Playgroud)
如果 ES6 是一个选项,您可以使用Set而不是辅助对象:
const array1 = [{"a":1,"b":"first"},{"a":2,"b":"second"}];
const array2 = [{"a":3,"b":"third"},{"a":1,"b":"fourth"}];
const result = array2.concat(array1).filter(function(o) {
return this.has(o.a) ? false : this.add(o.a);
}, new Set());
console.log(result);Run Code Online (Sandbox Code Playgroud)
如果要使用箭头函数,则不能使用thisArgofArray.filter()来绑定Setas thisthe 函数(不能绑定this到箭头函数)。您可以改用闭包(该方法的属性转到@NinaScholz)。
const array1 = [{"a":1,"b":"first"},{"a":2,"b":"second"}];
const array2 = [{"a":3,"b":"third"},{"a":1,"b":"fourth"}];
const result = [...array2, ...array1]
.filter((set => // store the set and return the actual callback
o => set.has(o.a) ? false : set.add(o.a)
)(new Set()) // use an IIFE to create a Set and store it set
);
console.log(result);Run Code Online (Sandbox Code Playgroud)