1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript【よく使う配列・オブジェクト処理まとめ】

Posted at

この記事では、よく使う配列・オブジェクトの処理の使い方とサンプルコードを一覧として残していきます。

※本記事は今後も必要に応じて随時更新していく予定です。


Object.keys(オブジェクトのキーを取得)

Object.keys() は、オブジェクトのキー(左側の値)だけを配列として取得したいときに使います。

サンプルコード

const user = {
  name: "Alice",
  age: 30,
  isAdmin: false,
};

console.log(Object.keys(user));
// 出力: ["name", "age", "isAdmin"]

Array.forEach(配列に対してループ処理)

forEachメソッドは、配列の各要素に対して指定したコールバック関数を実行する際に使用します。ループ処理を簡潔に記述できる。

サンプルコード

const array = [1, 2, 3, 4, 5];

array.forEach((element, index) => {
  console.log(`Index: ${index}, Element: ${element}`);
});
// Expected output:
// Index: 0, Element: 1
// Index: 1, Element: 2
// Index: 2, Element: 3
// Index: 3, Element: 4
// Index: 4, Element: 5

Array.includes(配列にある特定の値をチェック)

includesメソッドは、配列に特定の値が含まれているかどうかを確認するために使用します。配列に特定の要素が含まれているかを簡単に判定できます。

サンプルコード

const fruits = ["apple", "banana", "cherry"];

console.log(fruits.includes("banana")); // Expected output: true
console.log(fruits.includes("orange")); // Expected output: false

Array.map(配列の各要素に対して処理を行う)

mapメソッドは、配列の各要素に対して処理を行い、その結果を新しい配列として返すメソッドです。元の配列は変更されません。

サンプルコード

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map((num) => num * 2);

console.log(doubled);  // Expected output: [2, 4, 6, 8, 10]

Array.filter(条件に一致する要素を抽出)

filterメソッドは、条件に一致する配列の要素を新しい配列として抽出するメソッドです。特定の条件を満たす要素だけを取り出す際に使います。

サンプルコード

const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter((num) => num % 2 === 0);

console.log(evenNumbers);  // Expected output: [2, 4, 6]

Object.assign(オブジェクトをコピー)

Object.assign メソッドは、オブジェクトをコピーしたり、複数のオブジェクトをマージするために使われます。特に、オブジェクトのプロパティを他のオブジェクトにコピーする際に便利です。

サンプルコード

const person = { name: 'John', age: 30 };
const copyPerson = Object.assign({}, person);

console.log(copyPerson); // { name: 'John', age: 30 }
console.log(person === copyPerson); // false (別のオブジェクト)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?