Map vs Object in JavaScript
HTML-код
- Опубликовано: 9 фев 2025
- Want to learn some practical differences with how you interact with Maps and Objects in JavaScript?
---------- Course
Want to go deeper with Next.js? Join me in my Next Level Next.js course where over 29 videos and 8 hours of content we'll build a full application from start to finish. We use TypeScript, GraphQL, Prisma, Apollo, Mapbox, Firebase and lots more. courses.leighh...
---------- Connect
Join this channel - / @leighhalliday
Join me on Discord - / discord
Check out my course called Next Level Next.js! A full stack course covering GraphQL, TypeScript, Apollo, Prisma, auth and lots more! next.leighhalliday.com
A note about the swapObj method you used, it will actually be done in O(N^2) complexity due to reduce+spread are iterating twice, you can do it better by either using Object.fromEntries or Object.assign to iterate in O(N)
Thanks for the heads up Omri!
im looking at a lot of map related videos atm...
can anyone show a good example when to use maps over objects?
the web and apis are so json heavy/oriented, when does map even make sense...
probably in data wich have loads of arrays.. machine learning, ai? data wich changes a lot? realtime market data for example etc , thousands of tickers and values...
well i guess map is good to use when you literally have just key-value pairs... not objects with more than single keyvalue entry or smt?
wonder if Map feature is prequel to the new features they are adding to javascript soon.... the pipes, like elixir language has (other languages too... i assume these things have some name and some other language have it too.... functional languages?)
|> toUpperCase()
|> trim()
|> console.log(x)
where you can chain stuff like that,
ive never written one, but also Decorators are Stage 3 and seem interesting concept... very reusable code
Leigh Halliday, I actually love your channel and appreciate these small clips you put out. You always introduce me to something new as a growing developer! Thanks, ALOT!
Nice! Glad it helped, Kay. Thanks for the support!
Great video. If you're looking for a video topic or just generally taking suggestions, I would love to see you cover TypeScript generics and partials.
Here you go my friend ruclips.net/video/XKVGXu6_ygY/видео.html
Thank you for posting knowledge! For me, this channel and all the work you put in it helps me out. I started on the path of web development alone and I learned a great deal from your React videos. I really like the way you explain things, makes them easy to understand.
Thank you so much Toma!
@@leighhalliday you could have used the in keyword to iterate over the object
Thanks! I love tutorials when they go right to the point ❤
absolutely amazing and to the point comparison!
I love the way you organize the tutorial, pretty awesome!
Thanks Alii!! Glad you enjoyed it
very interesting. I've been programming JS and TS for almost 6 years, never used Map, although seems to be cool
I learned about it when developing with MobX, it preferred map over object for certain things.
i watched several videos on map object, I stopped here because you hit all the points. thank you
Great explanation and examples. We should really be using Maps more
Another great video. Thanks, I've been stuck on using an arrow function return with reduce. I didn't know you had to spread the acc.
Thanks so much Kev!
Extremely valuable. Thank you sir.
Thanks for the great instruction
❤
great instructional video!
Thank you, it helps me enormously
Awesome! Glad you enjoyed it Ahmed!
Hey.. just found out your video and love it! Do you have other videos that talks about the performance between Map and Plain Object? Thanks!
Not related to the topic but how are you getting a full height vertical output window in your vscode setup in the right panel? Is this a package?
how can I favorite methods like in 9:44?
Very good and useful but I wonder if you could mention how to use stringify with maps?
Looks like the answer is here stackoverflow.com/questions/29085197/how-do-you-json-stringify-an-es6-map
Nice video, thanks! I’d like to use Map more, just need to start.
Small note: you say in object the order isn’t guaranteed. Actually, it’s guaranteed, but in ‘some special way’ :) integer properties are sorted, others appear in creation order.
Thanks!! I didn't know that :) Honestly the order of an object has never bothered me... I think if I cared about order I would use an array.
@@leighhalliday .. or Map :)
OP, at 7:16, you mention that "ironically this is an object", but I'm not sure why it's ironic. When you console.log({ foo, bar}), you're not consuming an object, but you're creating an object using shorthand. You could have just as easily written it as console.log({ value, key }). Just curious if I'm missing something interesting there.
Hey Michael! You're not really missing anything... was just a liberal use of the word "ironic" haha... that I was using an object when talking about maps in a video that compares maps to objects.
@@leighhalliday ah... okay, cool. Thanks for review.
Thanks for the Informative video, Can you make a video about scaling a typescript projects in manageable way ?, what are the practise we want to flow ?
Hey! My advice would be to use it on strict mode… it’ll call out everything which will slow you down at the beginning but be a life saver when your code base grows.
I love the simplicity of Objects, or maybe I am biased cause I have been working with objects a lot. You mentioned there are performance benefits to using maps?
There may be, but I didn’t worry too much about performance when doing this video. Best to search for some benchmark comparisons
Thanks for that!
Glad you enjoyed it!
Wonderful, thank you!
You’re very welcome Chris!
What is the practicality of swapping the keys and values?
This video shows some of the differences between the two, but does not show why you would use one over the other.
OBJ over MAP
-If dealing with data from/to an API
--Due to JSON format is normally required
-if dealing with data that is always going to have the same keys
MAP over OBJ
-If you will delete and add new keys
--This is due to a slight speed up
PS: It is relatively simple to convert one to the other, but still it is still a thing
i am first...great content loooove it... i will finally know how to code 👨💻 thank you
First! Glad you enjoyed the content :)
i will be your padawan 🥷
I am struggling with DBs. Maybe a good idea to compare Supabase vs. Prisma? ease of use, speed, auth integration, dev speed...
I definitely need to give Supabase a try... I'll start learning it so I can make a video shortly.
You're the man
Hey, Leigh what theme you use in Vs code ?
Hey Maneth! It is OneMonokai I believe
@@leighhalliday thanks
Interesting how Python does it the other way round, with the expressions that look like JavaScript “object” ones actually constructing dictionaries, while general Python objects have custom construction facilities (or you could use canned ones like dataclasses).
Basically, JavaScript tried to mash dictionaries and general objects together, and then discovered this was not such a good idea, so it had to add a separate dictionary (Map) type anyway. Python kept them separate, and ended up with a cleaner and simpler design overall.
Python has really powerful expressions! I never quite mastered them but I’ve only worked professionally with python for a few months.
@@leighhalliday Have you tried Jupyter notebooks? A very handy tool for exploring programming and data manipulation and general messing about, not just in Python but also other languages.
I have a collection of Jupyter notebooks discussing various topics in Python. I would link to them, but RUclips will likely delete my comment.
You have to write custom logic when using Map unlike pojos
Great Video, but when should we use Map and when should we use Object ?
Very neat👍
Thanks Abdo!
const swapObj = Object.entries(obj).reduce((acc, [key, value]) => acc[value] = key && acc, {})
also works
As long as value !== 0 😄
Please continue uploading videos on your other Spanish channel Leigh, we are a great community waiting for Spanish-speaking people who value your content a lot, regards
Gracias John! Lo intentaré pero es difícil tener un balance entre RUclips y el resto de mi vida jaja. Gracias por tu apoyo!
@@leighhalliday lo entiendo gracias por darte el tiempo de escribir, tu información es precisa en lo mayoría de los casos, saludos desde Perú.
Clojure has ruined me, this all seems like so complicated for no reason lol.
Also this video is great
ty. also would be nice codepen for this, as a cheatsheet :D
Hey Alex! If this helps, here's a quick gist of the final code: gist.github.com/leighhalliday/31430d36b49e7296e7a2ef603e2084ef
@@leighhalliday wow ty! also add it to the description, so everyone who need it could see it :D
I prefer to use the .map() method over .reduce() when working with object structure.
const swapObj = Object.fromEntries(
Object.entries(obj).map(([key, value]) => [value, key])
);
good video!
Thanks Ale!
the notion that „in a js object the order is not guaranteed“ has been wrong for quite a few years now.
nowadays, the order is in fact guaranteed.
Just started watching the video but in my opinion is using map is not worth, leets see if I change my mind after the video
Did you change your mind?
@Leigh Halliday I agree when you say that maps are great if you just want a dictionary, but as you said later most of the time we interact with objects in the end and that's my biggest issue with maps. Maps API is really nice tho
I guess I've changed my mind because I will at least consider Maps depending on the context
When I do LeetCode questions always use an object.
I tend to use objects too… but I have never done a LeetCode question hehe
No need ; at the eol. Otherwise, the guide is generally good, although misses some alternatives, at least for object.
Just doing what prettier auto formats for me;
@@leighhalliday Sure, but sometimes it is worth to take a lead.
Thanks a lot for this video, it's exactly what I needed for my exam on Monday!
so basically maps are better than objects
I wouldn’t say so… when you work with JSON you’ll end up with an object, you get destructuring.
totally agree, but that's one situation where objects make sense. But are there many more situations? maps are even faster than objects
In one sense I'd say: Use objects when you define the properties, or are from parsing JSON... use maps when the keys come from data.