1

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.

3
  • Your question isn't very clear. Explain yourself better, and add code to show what you're trying to achieve Commented Apr 14, 2017 at 0:26
  • 1
    Is this what you are asking? stackoverflow.com/questions/29759480/… Commented Apr 14, 2017 at 0:30
  • @Andrew yeah that's roughly it - thanks. Commented Apr 14, 2017 at 1:00

1 Answer 1

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}`); } 
Sign up to request clarification or add additional context in comments.

2 Comments

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"
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. ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.