라이브러리
[JAVASCRIPT] Object.fromEntries(iterable) - `[키, 값]` 배열을 객체로 변환
Object.fromEntries(iterable)
=====================================
`Object.fromEntries(iterable)`는 JavaScript의 빌트인 메소드 중 하나로, iterable 객체를 사용하여 객체를 생성합니다. 이 메소드는 iterable 객체의 각 요소를 키-값 쌍으로 사용하여 객체를 생성합니다.
Syntax
--------
#hostingforum.kr
javascript
Object.fromEntries(iterable)
Parameter
------------
* `iterable`: iterable 객체. 이 객체는 키-값 쌍을 포함하는 배열, Map, Set, 또는 iterable 객체를 포함하는 객체를 지정할 수 있습니다.
Return Value
----------------
* 생성된 객체
예제
------
1. 배열에서 객체 생성
#hostingforum.kr
javascript
const array = [
['name', 'John'],
['age', 30],
['city', 'New York']
];
const person = Object.fromEntries(array);
console.log(person); // { name: 'John', age: 30, city: 'New York' }
2. Map에서 객체 생성
#hostingforum.kr
javascript
const map = new Map([
['name', 'John'],
['age', 30],
['city', 'New York']
]);
const person = Object.fromEntries(map);
console.log(person); // { name: 'John', age: 30, city: 'New York' }
3. 객체에서 객체 생성
#hostingforum.kr
javascript
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const person = Object.fromEntries(Object.entries(obj));
console.log(person); // { name: 'John', age: 30, city: 'New York' }
4. Set에서 객체 생성
#hostingforum.kr
javascript
const set = new Set([
['name', 'John'],
['age', 30],
['city', 'New York']
]);
const person = Object.fromEntries([...set]);
console.log(person); // { name: 'John', age: 30, city: 'New York' }
5. 객체에서 객체 생성 (중복 키 처리)
#hostingforum.kr
javascript
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const person = Object.fromEntries(Object.entries(obj));
console.log(person); // { name: 'John', age: 30, city: 'New York' }
// 중복 키 처리
const obj2 = {
name: 'Jane',
name: 25,
city: 'Seoul'
};
const person2 = Object.fromEntries(Object.entries(obj2));
console.log(person2); // { name: 25, city: 'Seoul' }
주의
----
* `Object.fromEntries(iterable)`는 iterable 객체의 각 요소를 키-값 쌍으로 사용하여 객체를 생성합니다. 따라서 iterable 객체의 요소가 중복 키를 포함하는 경우, 마지막 요소가 우선됩니다.
* `Object.fromEntries(iterable)`는 iterable 객체의 요소가 null 또는 undefined인 경우, 객체에 null 또는 undefined가 포함됩니다.
댓글목록
등록된 댓글이 없습니다.