JavaScript プロパティとオブジェクトの操作
JavaScript備忘録 Vol.8
目次
- プロパティの操作
- オブジェクトの操作
今回もJavaScriptの記事になっています。
プロパティの操作
ここではオブジェクトのプロパティの操作方法を見ていきます。
const fruit = { name: 'orange', price: 100, };
値の取得
2つの記法があります。
まず一つはオブジェクト名.キー
として取得する方法です
const fruit = { name: 'orange', price: 100, }; console.log(fruit.name);
orangeと出力されてますね
次はオブジェクト名['キー']
という形で[ ]
内にキーを文字列で渡します。
const fruit = { name: 'orange', price: 100, }; console.log(fruit['price']);
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']);
この様に再代入することでどちらの値もちゃんと変わっています。
キーの追加
また、この配列に原産国を追加しいたいとします。
その場合には新しくキーを追加してあげることができます
const fruit = { name: 'orange', price: 100, }; fruit.madeIn = 'Japan'; console.log(fruit);
オブジェクトにキーと値が追加されてますね。
削除
キーを削除してあげることもできます。
その際にはdelete オブジェクト名.キー
としてあげます。
const fruit = { name: 'orange', price: 100, }; delete fruit.price; console.log(fruit);
プロパティが 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);
一つのオブジェクトに2つのプロパティを追加し、計4つのプロパティができましたね。
同じ記事で紹介した分割代入とレスト構文も使用することができます。
例えばこの
name
とprice
を定数として使用できる様にしたかったとします。
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);
この様に分割代入
を使うことができ、
const { }
とし、キーと同じ定数名
を使用することで、キーの値が代入されます。
他の要素をプロパティのままオブジェクトのままにしたい場合には上記の様に
...others
としてレスト構文を使うことでオブジェクトのままにすることができます。
今回はここまで
次回は・・・まだまだJS!
それではまた次回!