Object property iteration in js

Object property iteration in js
0

#1

I am reading through YDKJS this and object prototypes.

The author mentioned 2 method of iterate an array.

1st: iterate over the indices.

var myArray = [1,2,3];
for(var i = 0; i<myArray.length; i++){
     console.log(myArray[i]);
}

2nd method: iterate directly on the value

var myArray = [1,2,3];
for(var v of myArray){console.log(v);}

This 2 methods both let you see how many and what each property you have in your array. This got me thinking what about a normal object? How do I list out all the properties in it? Because the author said the second method DOES NOT WORK on normal objects. Because objects do not have the built in @@iterator

Also in backend development, under what scenario do we need to use this kind of things?
I am thinking maybe I build a online registration system for a small motel. And after one day I want to list out all the people that are staying overnight? So I use this method to make a list or something? (sorry if this is quite an immature thought )


#2

These can help you to work with objects:



For the second part of the question, think Twitter or Facebook. You make a query to a database then iterate over it either to fill a template or to modify the information.


#3

[Putting aside the fact that everything in JS is an object]

  • An object is a collection of key:value pairs in no particular order. It’s not designed to be iterated over - to access a value, you look for the key in the object. You can iterate over them using a for...in loop, there are times when you need to iterate in some way. Or you can use Object.{keys,values,entries}as @Implaier says, converting the keys/values into an array.
  • An array is a collection of values in order. They have keys, representing indices, but you don’t generally access them like that, you iterate using a loop, or you use the Array methods provided by JS.

You can kinda think of an object like a dictionary, with the key as the word, and the value as the definition: when you use the dictionary, you look for a specific word in it.

In comparison, an array would be kinda like a list of all the words in the dictionary, in order. If you wanted to print all words beginning with a, you could take that list and filter it, and you’d get a list of all the a words in order.

In your example, each person might be an object, with a name, ID, contact details etc. But the overall collection of people staying would be a list


#4

ok i see.

thanks!

(20 character)