假设我们有一个像这样的对象-
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' }