Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

node.js - Union of array of objects in JavaScript

I'm trying to do union of different arrays:

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)

It's possible in my code that some or all array1, array2, array3 can be null, this is not shown in the code above.

However when one or more of them are null I get the error for example if array1 was assigned to null: array1 is not iterable.

How can I prevent getting this error?

question from:https://stackoverflow.com/questions/65939629/union-of-array-of-objects-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the nullish coalescing operator to fall back to an empty array if the 'array' is actually null.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...