Conversion between Javascript Object and Map

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
Object property names can only be string type codes insert image description here

Create a map type

new Map([
	[key, value],
	[key1, value1]
])

Briefly introduce the following two methods

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 属性名')

insert image description here

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)

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46112649/article/details/126038160
Recommended