0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript勉強の記録その14: Object.keys(オブジェクト名)を利用してオブジェクトのプロパティーを操作

Posted at

Objet.keys(オブジェクト名)を利用して、オブジェクトのプロパティーを操作

オブジェクトのプロパティーの値を全て取り出したい場合は、forEachは使えません。なぜならforEachは配列に対するメソッドだからです。

代わりにObject.keys(オブジェクト名)というメソッドを使い、オブジェクトのキーを取得し、取得したキーを利用してオブジェクトの値を取り出す方法があります。

まず、以下の例ではObject.keys()の基本的な動きを確認できます。

index.js
const point = {
  x: 100,
  y: 180,
};

const keys = Object.keys(point);
console.log(keys);
//=>["x", "y"]

keys.forEach(key => console.log(`Key: ${key}`));
//=>Key: x
//=>Key: y

Object.keys()を使うことで、キーを取得して配列に格納しているのがわかるかと思います。
この仕組みを利用してループ処理をしてあげれば、オブジェクトの各プロパティーへアクセスすることができます。

index.js
const point = {
  x: 100,
  y: 180,
};

const keys = Object.keys(point);
console.log(keys);
//=>["x", "y"]

keys.forEach(key => console.log(`Key: ${key} Value: ${point[key]}`));
//=>Key: x Value: 100
//=>Key: y Value: 180
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?