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