Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中对象数组的并集_Javascript_Node.js - Fatal编程技术网

JavaScript中对象数组的并集

JavaScript中对象数组的并集,javascript,node.js,Javascript,Node.js,我正在尝试合并不同的数组: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...array2, ...array3])] console.log(uni

我正在尝试合并不同的数组:

const info1 = {id: 1}
const info2 = {id: 2}
const info3 = {id: 3}

const array1 = [info1, info2]
const array2 = [info1, info3]
const array3 = [info2, info3]

const union = [...new Set([...array1, ...array2, ...array3])]

console.log(union)
在我的代码中,部分或全部array1、array2、array3可能为空,这在上面的代码中没有显示

但是,当其中一个或多个为null时,我会得到一个错误,例如,如果将array1分配给null:array1不可iterable

如何防止出现此错误?

如果“array”实际为空,则可以使用返回空数组


将代码修改为数组为空值,然后将空数组替换为空数组以正常工作,如下所示:

常量info1={id:1} 常量info2={id:2} const info3={id:3} 常量数组1=[info1,info2] 常量数组2=[info1,info3] 常量数组3=null const isNotNull=array=>array?数组:[] 常量并集=[…新集合[…isNotNullarray1,…isNotNullarray2,…isNotNullarray3]]
console.logunion您可以创建一个函数来为您执行额外的空检查

常量信息1={ 身份证号码:1 }; 常量信息2={ 身份证号码:2 }; 常量信息3={ 身份证号码:3 }; 常量数组1=[info1,info2]; 常量数组2=[info1,info3]; 常量数组3=[info2,info3]; 常量数组4=null; //这里的扩展运算符允许我们针对每个参数 //函数的性质 函数联合…数组{ //过滤器将删除*空*值 返回Array.fromnew Setarrays.filterx=>!!x.flat; }
console.logunionarray1、array2、array3、array4创建一个函数,该函数使用操作符循环遍历每个数组

检查是否为null,否则,添加到集合中

常量info1={id:1} 常量info2={id:2} const info3={id:3} 常量数组1=[info1,info2] 常量数组2=[info1,info3] 常量数组3=null; 函数createSet…全部{ //Tmp保持 设a=[]; //对于每个给定数组 对于变量i=0;iconsole.logcreateSetarray1、array2、array3 最简单的方法是使用带有默认数组的方法,用于带有数组或null的virable


…通过不使它们为空?或者在添加到集合之前检查它们是否为空?在联合之前进行空检查。这是我需要添加的一系列空检查?好的,是的,如果你想要数组,你可以使用数组,而且很容易,但是,如果您还需要null,您需要以某种方式处理它。为什么null保护不是解决方案?请注意,此运算符不受支持。arrays.flat.filterx=>!!x->这不应该是arrays.filterx=>!!x、 平坦的?想要知道空对象但忽略空数组似乎是有效的。@VLAZ yes true!
const union = [
  ...new Set([...(array1 ?? []), ...(array2 ?? []), ...(array3 ?? [])]),
];
unique = Array.from(new Set([array1, array2, array3].flatMap(v => v || [])));