Sean's Blog

An image showing avatar

Hi, I'm Sean

這裡記錄我學習網站開發的筆記
歡迎交流 (ゝ∀・)b

LinkedInGitHub

JavaScript Object Snippets

開發上,我們常常對物件做各種操作與應用,本文記載 Sean 常用到的物件操作方式。

hasOwnProperty

Object.prototype.hasOwnProperty()

會回傳一個布林值,判斷指定的屬性是否為該物件本身的屬性,而非繼承的屬性。

1const object1 = {};
2object1.property1 = 42;
3
4console.log(object1.hasOwnProperty('property1'));
5// Expected output: true
6
7console.log(object1.hasOwnProperty('property2'));
8// Expected output: false

實務上,我們在使用 for...in 的時候會搭配 hasOwnProperty() 一起使用。

因為 for...in 會遞迴物件裡面的每一個屬性名稱 (Key),而且會遞迴到繼承的屬性。因此可以使用 hasOwnProperty() 來排除繼承屬性,只使用本身的屬性執行給定的操作。

for...in

1for (const prop in obj) {
2  if (obj.hasOwnProperty(prop)) {
3    console.log(`obj.${prop} = ${obj[prop]}`);
4  }
5}

hasOwn

Object.hasOwn()

使用 hasOwn()hasOwnProperty() 的效果都一樣,只是寫法不同,但是實務上更建議使用 hasOwn(),因為相容性比較好。

1const object1 = {
2  prop1: 'exists',
3};
4
5console.log(Object.hasOwn(object1, 'prop1'));
6// Expected output: true
7
8console.log(Object.hasOwn(object1, 'prop2'));
9// Expected output: false

entries

將物件裡面的每個 Key-Value Pair 轉換為多個 Key-Value Pair 組成的陣列。

Object.entries()

可配合 for...of 取出陣列裡的每一組 [key, value]

for...of

1const obj = { a: 'something', b: 10 };
2console.log(Object.entries(obj)); // [ ['a', 'something'], ['b', 10] ]
3
4for (const [key, value] of Object.entries(obj)) {
5  console.log(`${key}: ${value}`);
6}
7// Expected output:
8// "a: somestring"
9// "b: 10"

keys

將物件裡面的 Key 提取為陣列。

Object.keys()

1const object1 = {
2  a: 'lorem',
3  b: 123,
4  c: false,
5};
6
7console.log(Object.keys(object1));
8// Expected output: Array ["a", "b", "c"]

values

將物件裡面的 Value 提取為陣列。

Object.values()

1const object1 = {
2  a: 'lorem',
3  b: 123,
4  c: false,
5};
6
7console.log(Object.keys(object1));
8// Expected output: Array ["lorem", 123, false]

assign

合併目標物件 (Source) 與一或多個來源物件 (Target),最後回傳該目標物件。

如果 Source 與 Target 有重複的屬性名稱,則 Source 會覆蓋掉 Target。

Object.assign()

1// Object.assign(target, ...sources);
2
3const target = { a: 1, b: 2 };
4const source = { b: 4, c: 5 };
5
6const returnedTarget = Object.assign(target, source);
7
8console.log(target);
9// Expected output: Object { a: 1, b: 4, c: 5 }
10
11console.log(returnedTarget === target);
12// Expected output: true

Object.assign 與展開運算子都是屬於 Shallow Copy,用的時候要知道會不會造成影響,否則容易踩雷。

真的需要複製物件,建議直接使用 JSON 操作或是 Lodash 提供的 _.cloneDeep() 方式。

References