Looping through js objects with “for in”

Posted on

in

So with arrays you can use map like so 
var array1 = [{name:"Mark"},{name:"Ben"}];

var mappedVar = array1.map((item, index) =>
             "Name " + (parseInt(index)+1) + " is "+ item.name)

console.log(mappedVar)

//returns ["Name 1 is Mark","Name 2 is Ben"]

To “map” through a js object use “for in”

var object1 = {1:{'name':'Mark'},2:{'name':'Ben'}};

var array = [];

var index = 0;
for (var item in object1){
  var person = object1[item]; //person is equal to eg. {'name':'Mark'}
  for (var data in person){
     if(data == "name"){
       array[index] = "Name " + (index+1) + " is "+ person[data] 
    }
  }
  index++;
}

console.log(array)

//returns ["Name 1 is Mark","Name 2 is Ben"]

First we get each item in the object and call it ‘person’ to make it easier to read. Then loop through it’s data to populate the array. In our example “data” is the key (eg. “name”) and “person[data] is the value (eg. “Mark”). We also manually update the ‘index’.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

July 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
293031