Mustafa HAMIT

JavaScript map() Kullanımı

JavaScript’te map() metodu, bir array içerisindeki her elemanı dönüştürerek yeni bir array oluşturmak için kullanılır.

Modern JavaScript geliştirme süreçlerinde en sık kullanılan array metodlarından biridir.

Bu yazıda JavaScript map() kullanımını örneklerle inceleyeceğiz.


map() Metodu Nedir?

map() metodu array içerisindeki her eleman için bir işlem gerçekleştirir ve sonuçlardan oluşan yeni bir array döndürür.

Temel kullanım:


array.map(function(item) {
  return item;
});

Basit map() Örneği


const numbers = [1, 2, 3];

const result = numbers.map(number => number * 2);

console.log(result);

Çıktı:


[2, 4, 6]

String Verilerde map() Kullanımı


const users = ["ahmet", "mehmet", "ayşe"];

const result = users.map(user => user.toUpperCase());

console.log(result);

Object Dizilerinde map() Kullanımı


const users = [
  { name: "Ahmet" },
  { name: "Mehmet" }
];

const result = users.map(user => user.name);

console.log(result);

Çıktı:


["Ahmet", "Mehmet"]

Yeni Property Ekleme


const users = [
  { name: "Ahmet" },
  { name: "Mehmet" }
];

const result = users.map(user => ({
  ...user,
  active: true
}));

console.log(result);

Index Kullanımı

map() metodu elemanın index değerine de erişebilir.


const fruits = ["Apple", "Orange", "Banana"];

const result = fruits.map((fruit, index) => {
  return `${index + 1} - ${fruit}`;
});

console.log(result);

map() ve forEach() Arasındaki Fark

MetodÖzellik
map()Yeni array döndürür
forEach()Yeni array döndürmez

Tüm Kullanımları İçeren Örnek


const products = [
  {
    name: "Laptop",
    price: 1000
  },
  {
    name: "Mouse",
    price: 50
  }
];

const result = products.map(product => ({
  ...product,
  priceWithTax: product.price * 1.2
}));

console.log(result);

map() Kullanım Alanları

  • API verilerini dönüştürme
  • Liste oluşturma
  • Frontend veri işleme
  • React bileşenlerinde veri gösterme
  • Object dizilerini düzenleme

Sonuç

JavaScript map() metodu array verilerini dönüştürmek için kullanılan en güçlü metodlardan biridir.

Özellikle API işlemleri ve modern frontend geliştirme süreçlerinde sık kullanılmaktadır.


Sık Sorulan Sorular (SSS)

map() ne işe yarar?

Array içerisindeki elemanları dönüştürerek yeni bir array oluşturur.

map() orijinal array’i değiştirir mi?

Hayır, yeni bir array döndürür ve orijinal array’i değiştirmez.

map() ile forEach() arasındaki fark nedir?

map() yeni bir array döndürür, forEach() ise sadece işlem yapar.

Loading

Bir yanıt yazın