Monday, February 24, 2020

Javascript Print array of objects and primitive types into console

There are many ways we can print java script array into console.

 Print array of primitive into console 

Following example explains about various things.
  • Array of strings are created inline using square brackets 
  • print the array at once using console.log - [ 'one', 'two', 'three' ] 
  • Used for of loop to iterate and print using console statements

let stringArray = ["one", "two", "three"];
console.log(stringArray);
for (let str of stringArray) {
    console.log(str);
}
Output is
one
two
three

Iterate using array for with callback function

 Using array each method to iterate with each element is applied with callback function
let stringArray = ["one", "two", "three"];

stringArray.forEach(function(str) {
    console.log(str);
});

Object keys function using map method 

Object is an class in java script which has keys method accepts string array, returns array of strings of enumerable properties. callback in map is called for each element.
Object.keys(stringArray).map(str => console.log(stringArray[str]))

Print array of objects into console in javascript 

array can contain multiple objects, each object contain key and value pairs enclosed in {}. Using JSON.stringfy used to print the object in json in string format.
let employees = [{ "id": 1, "name": "kiran" }, {
    "id": 2,
    "name": "franc"
}]
console.log(employees);
console.log(JSON.stringify(employees));
[ { id: 1, name: 'kiran' }, { id: 2, name: 'franc' } ]
[{"id":1,"name":"kiran"},{"id":2,"name":"franc"}]

Related article


EmoticonEmoticon