다음과 같은 객체가 있다고 가정해 보겠습니다. -
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharasthra",
salary: "146000"
}; 이러한 객체를 키 값 쌍으로 가져와 이를 Map으로 변환하는 JavaScript 함수를 작성해야 합니다.
예시
이에 대한 코드는 -
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharasthra",
salary: "146000"
};
const objectToMap = obj => {
const keys = Object.keys(obj);
const map = new Map();
for(let i = 0; i < keys.length; i++){
//inserting new key value pair inside map
map.set(keys[i], obj[keys[i]]);
};
return map;
};
console.log(objectToMap(obj)); 출력
콘솔의 출력 -
Map(5) {
'name' => 'Jai',
'age' => 32,
'occupation' => 'Software Engineer',
'address' => 'Dhindosh, Maharasthra',
'salary' => '146000'
}