Simple distinction between Map and Object
Map is a type exited by ES6. Features: Any value can be used as a property name
Object features: attribute names can only be strings (I didn't believe it at first, but I found out after testing)
the code | picture |
---|---|
Create a map type
new Map([
[key, value],
[key1, value1]
])
Briefly introduce the following two methods
- The Object.entries() method returns an array whose members are key-value pairs of all traversable (enumerable) properties of the parameter object itself (excluding inherited ones).
- The Object.fromEntries() method is the inverse operation of Object.entries() , which is used to convert an array of key-value pairs into an object.
Object type to Map type
The characteristics of Object.entries are mainly used here.
Object.entries returns a two-dimensional array, where the first value in the array is key, and the second value is value
const obj = {
a: '我是obj.a',
b: '我是obj.b',
c: '我是obj.c',
}
console.log(obj)
const map = new Map(Object.entries(obj))
console.log(map)
console.log(map.get('a'), '我是map 属性名')
console.log(map.get('b'), '我是map 属性名')
Map type to Object type
const arr = [1, 2, 3],
obj = {
a: '1', b: 2 },
number = 22
const map = new Map()
map.set(arr, '我是map的第1个值,我是数组')
map.set(obj, '我是map的第2个值,我是对象')
map.set(number, '我是map的第3个值, 我是简单数据类型')
const newObj = Object.fromEntries(map.entries())
console.log(newObj, '我是新对象')
console.log('新对象类型', typeof newObj)