Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a javascript Set with objects?

Tags:

javascript

I have a json file businessList.json with the following

[
{"availableTimes": [{"type": "time", "time": "06:30"}, {"type": "time", "time": "07:00"}]},

{"availableTimes": [{"type": "time", "time": "08:30"}, {"type": "time", "time": "07:00"}]}
]

In another file, I am trying to create a set out of this, but it won't work, it'll show all of the duplicate values. I'm assuming it's because of how objects are passed by reference. How could I solve this to get to the desired result?

const timesAvailable = new Set()
businessList.map(item => item.availableTimes.map(item => timesAvailable.add(item))) //won't work
like image 736
uber Avatar asked Jan 26 '26 11:01

uber


1 Answers

Like the first comment by Pointy says, objects are only equal to each other in JavaScript if they refer to the same place in memory. For example,

const object1 = { foo: 'bar' };
const object2 = object1;

object1 === object2 //true;
{ foo: 'bar' } === { foo: 'bar' } //false

There isn't any way around it with Set. One thing I've done in a similar situation is loop through the array and create a dictionary (either with a JavaScript Object or Map), generating a unique key for each item, then iterating through that Object or Map to get the unique times.

For example, in your case, something like:

const availableTimesMap = availableTimes.reduce((acc, timeObject) => {
  const key = `${timeObject.type}-${timeObject.time}`;
  acc[key] = timeObject;
}, {});

const uniqueTimes = Object.values(availableTimesMap);

Hope this helps. Let me know if you have any questions.

like image 121
sdotson Avatar answered Jan 29 '26 01:01

sdotson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!