Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Object.keys().map() VS Array.map() in JavaScript
Following is the code showing Object.keys().map() and Array.map() in JavaScript −
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>Object.keys().map() VS Array.map()</h1>
<div class="sample">{1:'A',22:'B',55:'C',19:'D'}</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to sum the keys of the above object</h3>
<div class="sample">[22,33,11,44]</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to double each element of the above array</h3>
<script>
let resEle = document.querySelectorAll(".result");
let BtnEle = document.querySelectorAll(".Btn");
let obj = { 1: "A", 22: "B", 55: "C", 19: "D" };
let arr = [22, 33, 11, 44];
let total = 0;
BtnEle[0].addEventListener("click", () => {
Object.keys(obj).map((x) => (total += parseInt(x)));
resEle[0].innerHTML = "The sum of the object keys = " + total;
});
BtnEle[1].addEventListener("click", () => {
resEle[1].innerHTML = arr.map((x) => x * 2);
});
</script>
</body>
</html>
Output
The above code will produce the following output −

On clicking the first ‘CLICK HERE’ button −

On clicking the second ‘CLICK HERE’ button −

Advertisements