객체의 메소드
자바스크립트의 모든 것은 사실상 객체이다. 이는 문자열이나 배열 등이 object의 프로토타입을 상속받는다는 의미이다. 따라서 다른 타입의 메소드와 달리 객체의 메소드는 대부분 Object 프로토타입에 걸려있는 정적 메소드이다.
객체를 배열로 : keys()∙values()∙entries()
이 메소드들은 객체로부터 직접 찾은 열거 가능한 문자열을 요소로 하는 배열을 반환한다. 배열도 객체이기 때문에 values()를 통해 배열을 복제하는 방식도 사용할 수 있다.
// 단순 배열 const arr = ["a", "b", "c"]; Object.keys(arr) // console: ['0', '1', '2'] // 유사 배열 (숫자를 속성으로 사용하는 객체) var obj = { 0: "a", 1: "b", 2: "c" }; Object.values(obj) // ['a', 'b', 'c'] // 유사 배열의 경우 속성으로 사용한 숫자의 크기 순으로 정렬되어 반환된다 var obj = { 100: "a", 2: "b", 7: "c" }; Object.values(obj) // ['b', 'c', 'a'] // entries는 튜플로 이루어진 배열을 반환한다 const obj = { a: 5, b: 7, c: 9 }; Object.entries(obj) // [ ['a', 5], ['b', 7], ['c', 9] ]
배열을 객체로 : fromEntries()와 groupBy()
fromEntries()는 [key, value] 튜플로 이루어진 배열을 받아서 객체로 만든다. entries()의 반대 버전이라고 생각하면 좋다.
const entries = [ ["foo", "bar"], ["baz", 42], ]; Object.fromEntries(entries) // { foo: "bar", baz: 42 }
groupBy()는 제공된 콜백 함수가 반환하는 문자열 값에 따라 주어진 순회 가능한 여러 요소를 그룹화한다. 반환된 객체는 각 그룹에 대해 별도의 속성을 가지며, 이 속성들은 해당 그룹의 요소들을 포함하는 배열을 담고 있다. 반환된 객체와 원본 순회 가능한 여러 요소는 동일하다.
const inventory = [ { name: "asparagus", type: "vegetables", quantity: 5 }, { name: "bananas", type: "fruit", quantity: 0 }, { name: "goat", type: "meat", quantity: 23 }, { name: "cherries", type: "fruit", quantity: 5 }, { name: "fish", type: "meat", quantity: 22 }, ]; const result1 = Object.groupBy(inventory, ({ type }) => type); const result2 = Object.groupBy(inventory, ({ quantity }) => return quantity > 10 ? "ok" : "restock"; ); // result1 { vegetables: [ { name: 'asparagus', type: 'vegetables', quantity: 5 }, ], fruit: [ { name: "bananas", type: "fruit", quantity: 0 }, { name: "cherries", type: "fruit", quantity: 5 } ], meat: [ { name: "goat", type: "meat", quantity: 23 }, { name: "fish", type: "meat", quantity: 22 } ] } // result2 { restock: [ { name: "asparagus", type: "vegetables", quantity: 5 }, { name: "bananas", type: "fruit", quantity: 0 }, { name: "cherries", type: "fruit", quantity: 5 } ], ok: [ { name: "goat", type: "meat", quantity: 23 }, { name: "fish", type: "meat", quantity: 22 } ] }
존재 여부 : hasOwn()
hasOwn()은 객체가 특정 속성을 직접적으로 가지고 있는지 확인하는 데 사용된다. 따라서 in 연산자와 달리 객체의 프로토타입 체인에서 지정된 속성은 확인해주지 않는다.
const example = { prop: "value" } // `hasOwn` 은 오직 직접적인 속성만 true를 반환한다. Object.hasOwn(example, "prop"); // true Object.hasOwn(example, "toString"); // false // `in` 연산자는 직접적인 속성 혹은 상속된 속성이 있을 경우 true를 반환한다. "prop" in example; // true "toString" in example; // true
객체에는 열거 가능하지 않은 속성도 포함되어있기 때문에, 객체의 키를 순회하기 위해서는 Object.keys를 통해 객체를 배열로 변환하고 for … of 를 돌아야 한다. 하지만 hasOwn을 사용하면 열거 불가능한 상속된 속성을 건너뛸 수 있어 for … in 으로 순회할 수 있다.
const example = { foo: true, bar: true }; // 객체를 배열로 전환하여 순회 for (const name of Object.keys(example)) { console.log(name) } // 배열 전환 없이 순회 가능한 값들로만 순회 for (const name in example) { if (Object.hasOwn(example, name)) { console.log(name) } }
배열도 객체인 까닭에 특정 인덱스가 존재하는지를 확인하는데도 hasOwn()이 유용하게 사용된다. 음수의 인덱스에 접근하는 경우 무조건 false를 반환한다. (이유는 [ Array[index] 사용을 그만둬라 애송이 ] 포스트에서 확인할 수 있다)
const fruits = ["Apple", "Banana", "Watermelon", "Orange"]; Object.hasOwn(fruits, 3); // true ('Orange') Object.hasOwn(fruits, 4); // false Object.hasOwn(fruits, -1); // false
블로그의 정보
Ayden's journal
Beard Weard Ayden