男子プログラマーになりたいやつ

未経験から一端のエンジニア目指し日々勉強中です。

JavaScript プロパティとオブジェクトの操作

<a class="keyword" href="http://d.hatena.ne.jp/keyword/JavaScript">JavaScript</a> オブジェクト編 vol.5 f:id:TomozQ:20201104223042j:plain

JavaScript備忘録 Vol.8

目次
  • プロパティの操作
  • オブジェクトの操作




今回もJavaScriptの記事になっています。

プロパティの操作

ここではオブジェクトのプロパティの操作方法を見ていきます。

const fruit = {
    name: 'orange', 
    price: 100,
};



値の取得

2つの記法があります。

まず一つはオブジェクト名.キーとして取得する方法です

const fruit = {
  name: 'orange', 
  price: 100,
};

console.log(fruit.name);

f:id:TomozQ:20201104222309p:plain

orangeと出力されてますね


次はオブジェクト名['キー']という形で[ ]内にキーを文字列で渡します。

const fruit = {
  name: 'orange', 
  price: 100,
};

console.log(fruit['price']);

f:id:TomozQ:20201104222300p:plain

100と出力されていますね。


値の変更

例えばorangeをappleに、100を120に変更したいとします。

その場合は

const fruit = {
  name: 'orange', 
  price: 100,
};

fruit.name = 'apple';
fruit['price'] = '120';

console.log(fruit.name);
console.log(fruit['price']);

f:id:TomozQ:20201104222246p:plain

この様に再代入することでどちらの値もちゃんと変わっています。


キーの追加

また、この配列に原産国を追加しいたいとします。

その場合には新しくキーを追加してあげることができます

const fruit = {
  name: 'orange', 
  price: 100,
};

fruit.madeIn = 'Japan';

console.log(fruit);

f:id:TomozQ:20201104222235p:plain

オブジェクトにキーと値が追加されてますね。


削除

キーを削除してあげることもできます。

その際にはdelete オブジェクト名.キーとしてあげます。

const fruit = {
  name: 'orange', 
  price: 100,
};

delete fruit.price;

console.log(fruit);

f:id:TomozQ:20201104222222p:plain

プロパティが name: 'orange' だけになりましたね。




オブジェクトの操作

以前の記事で配列に対してのスプレッド構文を紹介しましたが、オブジェクトに対しても使うことができます

const otherProps = {
  madeIn: 'Japan',
  color: 'red';,
};

const fruit = {
    name: 'orange', 
    price: 100,
};

この様に2つのオブジェクトがあり、otherPropsのプロパティをfruitに追加したいとします。

その場合には

const otherProps = {
  madeIn: 'Japan',
  color: 'red',
};

const fruit = {
    name: 'orange', 
    price: 100,
    ...otherProps,
};

console.log(fruit);

f:id:TomozQ:20201104222212p:plain

一つのオブジェクトに2つのプロパティを追加し、計4つのプロパティができましたね。


同じ記事で紹介した分割代入とレスト構文も使用することができます。

例えばこの

namepriceを定数として使用できる様にしたかったとします。

const otherProps = {
  madeIn: 'Japan',
  color: 'red',
};

const fruit = {
    name: 'orange', 
    price: 100,
    ...otherProps,
};

const{name, price, ...others} = fruit;

console.log(name);
console.log(price);
console.log(others);

f:id:TomozQ:20201104222202p:plain この様に分割代入を使うことができ、
const { }とし、キーと同じ定数名を使用することで、キーの値が代入されます。
他の要素をプロパティのままオブジェクトのままにしたい場合には上記の様に
...others
としてレスト構文を使うことでオブジェクトのままにすることができます。




今回はここまで

次回は・・・まだまだJS!

それではまた次回!