将对象转换为映射-JavaScript
假设我们有一个像这样的对象-
const obj = {name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
};
我们需要编写一个JavaScript函数,该函数接受带有键值对的此类对象并将其转换为Map。
示例
让我们为此编写代码-
const obj = {name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
const objectToMap = obj => {
const keys = Object.keys(obj);
const map = new Map();
for(let i = 0; i < keys.length; i++){
//在映射内插入新的键值对
map.set(keys[i], obj[keys[i]]);
};
return map;
};
console.log(objectToMap(obj));
输出结果
控制台中的输出:-
Map(6) {'name' => 'Vikas',
'age' => 45,
'occupation' => 'Frontend Developer',
'address' => 'Tilak Nagar, New Delhi',
'experience' => 23,
'salary' => '98000'
}
以上是 将对象转换为映射-JavaScript 的全部内容, 来源链接: utcz.com/z/355687.html