引用加参考:blog.csdn.net/lianjiuxiao…
前言
原生js能够支持这几种类型数据格式之间的转换,Object.entries和Object.FromEntries这两个原生方法的作用:
- Object.entries获取对象的键值对,返回的是一个数组
let obj={'foo':'hello','bar':100};
let arr=Object.entries(obj);
console.log(arr);//[ [ 'foo', 'hello' ], [ 'bar', 100 ] ]
- Object.FromEntries把键值对列表转成对象
let arr=[['foo','hello'],['bar',100]];
let obj=Object.fromEntries(arr);
console.log(obj);//{ foo: 'hello', bar: 100 }
- Object.entries和Object.fromEntries之间是可逆的
1、Object和Map之间转换
map转对象
// let map=new Map([['foo','hello'],['bar',100]]);
let map = new Map();
map.set('foo','hello')
map.set('bar',100)
let obj=Object.fromEntries(map);
console.log(obj);
对象转map
let obj={foo:'hello',bar:100};
let map=new Map(Object.entries(obj));
console.log(map)
2、Object和Array之间转换
主要用到的是前言章节提到的两种原生方法:Object.entries和Object.fromEntries