While solving LeetCode questions, I noticed I'd not fully understood Object and Array. So, I learned the fundamentals of Object again, and this blog is more like a study note for myself. But I hope it helps those of you who've got stuck with the same problems.
This article includes:
- basics
- for ... in
- hasOwnProperty()
- Object.keys(), Object.values(), Object.entries()
- forEach
Basics
Object is a collection of related data and/or functionality (MDN).
Property means key: value
, where key is a string and also called 'property name.'
We can check if a certain key exists in an object.
for ... in
So, by using key in object
along with a for loop, we can get all the keys or values of an object.
hasOwnProperty()
Another way to check the existence of a key in an object is hasOwnProperty().
property means key. It returns true or false
*It returns true even when the value is 'undefined' or 'null'.
It is useful for "hash table" questions.
Object.keys()
This returns an array of a given object's own enumerable string-keyed property names (MDN).
It returns in the key's numeric order (ascending).
The returned keys are strings.
Object.values()
This returns an array of a given object's own enumerable string-keyed property values (MDN).
It returns an array in the key's numeric order if the keys are numeric.
Object.entries()
This returns an array of a given object's own enumerable string-keyed property key-value pairs (MDN).
It returns in the key's numeric order (ascending).
forEach
array.forEach(callback)
forEach()
iterates over the array items, but if we use Object.keys(), Object.values(), or Object.entries, we can still get values because those return an array.
There're more Object methods, but the above would make it easier to solve coding problems and work with JSON.
Top comments (0)