How can I convert an array to a Set in JavaScript, and is there a way to access or delete elements by key instead of index?

I have an array of objects like:

var array = [
  { name: "malcom", dogType: "four-legged" },
  { name: "peabody", dogType: "three-legged" },
  { name: "pablo", dogType: "two-legged" }
];

I’m exploring whether I can convert this array to Set in JavaScript to remove items (e.g., .delete()), but I’m unsure if Set is the right structure since I want to access or modify objects by a key (name).

Is there a way to do this conversion without manually looping? Or should I consider a Map instead?

If you only care about uniqueness of objects by reference, you can create a Set like this:

const set = new Set(array);

However, you can’t delete by key (name), you’d need the exact object reference: t

set.delete(array[0]); // works
set.delete({ name: "malcom", dogType: "four-legged" }); // doesn't work (different reference)

So, Set isn’t ideal if you need key-based access.

If your goal is to access or delete items by a key (name), use a Map:

const map = new Map(array.map(item => [item.name, item]));

// Access
map.get("pablo"); // {name: "pablo", dogType: "two-legged"}

// Delete
map.delete("malcom");

This gives you clean key-based control over your data, and you can still iterate over the Map.

If you want both uniqueness and key-based lookup:

const uniqueSet = new Set(array.map(JSON.stringify)); // To remove duplicates
const finalMap = new Map([...uniqueSet].map(s => {
  const obj = JSON.parse(s);
  return [obj.name, obj];
}));

This is overkill for many use cases but combines deduplication with key-based access.