JavaScript中的对象到映射的转换
假设我们有一个像这样的对象-
const obj = { name: "Jai", age: 32, occupation: "Software Engineer", address: "Dhindosh, Maharasthra", salary: "146000" };
我们需要编写一个JavaScript函数,该函数接受带有键值对的此类对象并将其转换为Map。
示例
为此的代码将是-
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++){ //在映射内插入新的键值对 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' }