Cheat Sheet: Iterating over Arrays and Objects in Javascript

Cheat Sheet: Iterating over Arrays and Objects in Javascript

A review of some Array and Object methods for data handling

The context

I recently went through a "pair programming" interview for a React developer position, and was not very pleased with the way I performed at some rather simple data handling.

I realized I was really used to my data sets being based on arrays. And after rushing into it and getting a 'map is not a function' error, I realized the data sample I was supposed to work on was, instead, an object.

via Gfycat

I managed to cope though with the help of my google friend, but it cost me time, confidence, and did not make me look good. TBH, I delivered poorly.

I know. This is pretty basic stuff. Also, I have done it before. But when being interviewed, its good to be really 'fluent' in that kind of basic operations, because, you know, time is precious in these situations, and you want to be focused on the logic, not the technicalities.

So I decided I would look into it, get a clear understanding of how I should be manipulating data in these situations. I came up with a cheat sheet with lots of useful methods to use, and describing the way they work. This is a transposition of this cheat sheet into a technical article which I hope can be useful to you one day :)

Reminder: iterating on Arrays with Array.forEach and Array.Map

So, say, we have a simple array like this:

const colorArray =  ["red", "blue", "green", "white"];

If we want to alter its values (MUTATE it), we can run through it with Array.forEach. This allows us to update the value of each element using a loop.

//Simple forEach:
colorArray.forEach((element) => {
           //Do something 
});

//Now, we might be tempted to do that:

colorArray.forEach((element) => {
           element = someNewValue
});

/*** BUT RESULT WILL BE the original array unmutated
 * console: (4) ["red", "blue", "green", "white"]
 */

It is because we try to assign a value to the current element itself, where we should be trying to assign a new value to colorArray[currentElementIndex]

So we need to change the way we use forEach here and add the index.

colorArray.forEach((element, index) => {
  /*Say we add the index to the color code just to illustrate*/
  colorArray[index] = element+'-'+index 
})

// CONSOLE.LOG: (4) ["red-0", "blue-1", "green-2", "white-3"]

We can also use the Array.map method. Map is "kinda" like forEach, but will RETURN some content, creating a NEW ARRAY instead of mutating the original one. You use it in React a lot for example when you want to generate an array of JSX element to be rendered in the UI.

const newArrayFromMap = colorArray.map((element) => {
      return element.substring(0, 1) 
});

image.png

This is pretty standard, just wanted to make sure we're on the same page here :)

Iterating on objects (Well, not really)

Let's try mapping an object

Ok so, now, say, we have gotten those color values from an API, and got this data sample instead of an array:

const propertiesObject = {
  red: {
    color: "redColorCode"
  },
  blue: {
    color: "blueColorCode"
  },
  green: {
    color: "greenColorCode"
  },
  white: {
    color: "whiteColorCode"
  }
};

And it so happens we want to do something for each value of this dataset. Because we are hopeful and unconditionally positive individuals, we try this.

propertiesObject.map(element => {
    return element
})

And get 'rewarded' with that:

(parameter) element: any propertiesObject.map is not a function

We wont' be able to use map of forEach, because they are methods belonging to the Array Object. And this is pretty annoying!

However, luckily for us, we can use three methods of the "Object" object to extract whatever is in that object and turn it into an array:

  • Object.keys()
  • Object.values()
  • Object.entries()

Let's see what each of these do!

Object.keys()

This has been the first method of Object available to allow us to iterate through our object properties. It has been released with ES2015 (ES6), so it is not THAT old. Let's look at an example, and I'll explain:

const arrayOfKeys = Object.keys(propertiesObject);
console.log(arrayOfKeys); // (4) ["red", "blue", "green", "white"]

Now essentially, what Object.keys does is that it extracts the NAME of all first level properties in the object.

And this is good for us, because now, we can iterate on that array with maps and "BUILD" an array from our original object:

//Now we can construct the array we want, but we still have to access
//The original object to get the value of the color property.

const arrayOfObjectsFromKeys = arrayOfKeys.map(key => {
      return {[key]: {color: propertiesObject[key].color}} 
      //Notice, in the line above, how we define the property name to
      //be equal to the value of the current Key (using [key] : value syntax)
})

image.png

Object.values()

Object.values() was introduced, later, with ES2017. It allows you to extract only the values of the top level property of the object, and turn it into an array. Let's see what it does:

const arrayOfValues = Object.values(propertiesObject);

image.png

Pretty straightforward!

Object.entries()

Finally, for situations where we want to extract both keys and values, we can use Object.entries() (Also introduced in ES2017)

const arrayFromObject = Object.entries(propertiesObject);

Note this will make everything an array, even nested objects!

image.png

Now, let's say we want an 'array of objects', not an 'array of arrays'. Then we can use Object.entries and map it to get the desired format, like this:

const arrayOfObjects = Object.entries(propertiesObject).map((keyAndValue) => {
  //Then here we create the object we want
  return { [keyAndValue[0]]: { color: keyAndValue[1].color } };
  //Notice, in the line above, how we define the property name to
  //be equal to the value of the current Key (using [key] : value syntax
});

image.png

Turning the array back into an object using Object.assign

Now, say I have altered my new array and want to turn it back to into an object to return a new state for example or something:

We use Object.assign to populate a new object with the content of the array:

const backToAnObject = Object.assign({}, ...arrayOfObjects);

Gives us:

image.png

BONUS! Another way of creating the array of objects: the for/in loop

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

// We can use a for in loop to iterate on the object directly!
const arrayFromForInLoop = []
for (let key in propertiesObject) {
      arrayFromForInLoop.push(key, propertiesObject[key]);
}

image.png

I hope you enjoyed this, please feel free to ask questions or provide feedback :)

The actual 'cheat Sheet' can be found on this codepen:

codesandbox.io/s/iterating-on-arrays-and-ob..

via GIPHY