一、Object.entries()
Object.entries()
方法返回一个给定对象自身可枚举属性的键值对数组。
其排列与使用 for...in
循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)。
比如:
const obj = { name: 'jimmy', age: 18 } const entries = Object.entries(obj) console.log("entries:", entries)
结果如下:
二、Object.fromEntries()
Object.fromEntries()
方法把键值对列表转换为一个对象。
1、Object 转换操作
const obj = { name: 'jimmy', age: 18 } const entries = Object.entries(obj) console.log(entries) // [Array(2), Array(2)] const fromEntries = Object.fromEntries(entries) console.log(fromEntries) // {name: "jimmy", age: 18}
2、Map 转 Object
const map = new Map() map.set('name', 'jimmy') map.set('age', 18) console.log(map) // {'name' => 'jimmy', 'age' => 18} const obj = Object.fromEntries(map) console.log(obj) // {name: "jimmy", age: 18}
3、过滤
const course = { math: 80, english: 85, chinese: 90 } const res = Object.entries(course).filter(([key, val]) => val > 80) console.log(res) // [ [ 'english', 85 ], [ 'chinese', 90 ] ] console.log(Object.fromEntries(res)) // { english: 85, chinese: 90 }
4、url的search参数转换
const queryString = "?name=jimmy&age=18&height=1.88"; const queryParams = new URLSearchParams(queryString); const paramObj = Object.fromEntries(queryParams); console.log(paramObj); // { name: 'jimmy', age: '18', height: '1.88' }