0

I have a few objects that are all disparate, but which all have an id field. I want to create a Set() to hold these, but am not sure how to specify this field to the Set constructor/prototype/etc. Is this doable?

Let's say I have two types of objects (I'll give typescript definitions for simplicity's sake):

interface Thing1 {
  id: string;
  someData: string[]
}

interface Thing2 {
  id: string;
  someString: string;
  someOtherString: string
}

Now, I have two Arrays of these things, let's call them

array1: Thing1[];
array2: Thing2[];

What I'd like to do is create a new Set(array1) and then add each Thing2 in array2, performing a conditional merge of the two arrays.

The unique key in each of these is the id field - I was hoping there was some overloaded constructor or similar pattern that could be given a lambda (a la new Set(array1, (item) => item.id), maybe) which would specify the key to hash on for identity.

a p
  • 2,785
  • 2
  • 22
  • 40

1 Answers1

0

Working with a Set is pretty straightforward...

Imagine that you have two objects like so:

const obj1 = {
  id: 1,
  prop: 'Foo'
};

const obj2 = {
  id: 2,
  prop: 'Bar'
};

To create your Set with references to these objects, you can do this:

let set = new Set([obj1, obj2]);

Or that:

let set = new Set();
set.add(obj1).add(obj2);

Since a Set is an iterable object, you can use a for...of loop to retrieve all your data:

for (const obj of set) {
  console.log(`${obj.id}:${obj.prop}`);
}
Badacadabra
  • 5,385
  • 7
  • 23
  • 42
  • Not quite what I meant - I've added some examples, but it looks like the answer is just "You can't do that in JS" – a p Apr 14 '17 at 01:00
  • 1
    Oh, I see... I am sorry, your description was a bit unclear. I thought you wanted to know how to use the data structure in a traditional way. ;) – Badacadabra Apr 14 '17 at 01:24