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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With