object JavaScript选择 map而非对象存储键值对的 5 个理由附示例( 二 )


Object
将对象合并到数组中
let obj = { 1: 'one', 2: 'two'};Array.from(obj) // []//你必须这样Array.from(Object.entries(obj))//[ ['1', 'one'],['2', 'two'] ]//或者[...Object.entries(obj)]//[ ['1', 'one'],['2', 'two'] ]原因五:你可以很容易地检查其大小
Map
Map有一个内置的size属性 , 可以返回其大小 。
let map = new Map([1, 'one'], [true, 'true']);map.size // 2
Object
要检查对象的大小 , 必须将object .keys()和.length结合起来
let obj = { 1: 'one', true: 'true' };Object.keys(obj).length // 2缺点呢?没有用于序列化和解析的原生方法
Map
map原生不支持序列化或解析JSON 。
文档建议使用可以传递给JSON.stringify(obj, replacer)的replacer参数来实现你自己的方法 。和传入JSON.parse (string,reviver)的reviver
Object
你可以使用原生的JSON.stringify()和JSON.parse()来序列化和解析JSON对象 。
2个替换objectwithmap的例子
#1计算电子商务购物车的总价格和商品
这是JavaScript .reduce()函数完整指南中的一个例子
给定下面的数组
const shoppintCart = [{ price: 10, amount: 1 },{ price: 15, amount: 3 },{ price: 20, amount: 2 },
我们希望返回一个类似{totalItems: 6, totalPrice: 45}的对象 。
这是原始代码
shoppintCart.reduce((accumulator, currentItem) => {return {totalItems: accumulator.totalItems + currentItem.amount,totalPrice:accumulator.totalPrice + currentItem.amount * currentItem.price,},{ totalItems: 0, totalPrice: 0 } //初始化对象// { totalItems: 6, totalPrice: 45 }
这是使用Map的版本
shoppintCart.reduce((accumulator, currentItem) => {accumulator.set('totalItems', accumulator.get('totalItems') + currentItem.amount);accumulator.set('totalPrice', accumulator.get('totalPrice') + currentItem.price);return accumulator;},new Map([['totalItems', 0], ['totalPrice', 0]])// { 'totalItems' => 6, 'totalPrice' => 45 }
#2从数组中删除重复对象的另一种方法
这是我在开始学习JavaScript时在制作bookshelf应用程序时用到的一段代码 。
通过搜索如何从数组中删除重复对象 , 我找到了下面分享的示例 。
这是一个包含一个重复对象的数组
const books = [{ id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' },{ id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' },{ id: 2, title: 'The Alchemist', author: 'Paulo Coelho' },
下面是一种删除重复内容的特殊方法:
const uniqueObjsArr = [...new Map(books.map(book => [book.id, book])).values()
上面的单行代码发生了太多事情 。让我们把它分解成块 , 这样它就容易消化 。
// 1. 将数组映射为一个包含`id`和`book`的数组const arrayOfArrays = books.map(book => [ book.id, book ])// arrayOfArrays:[ 1, {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' } ],[ 1, {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' } ],[ 2, { title: 'Alchemist', author: 'Paulo Coelho' } ]// 2.由于键必须是唯一的 , 重复的键会被自动删除const mapOfUniqueObjects = new Map(arrayOfArrays)// mapOfUniqueObjects:1 => {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie'},2 => { title: 'Alchemist', author: 'Paulo Coelho' }// 3. 将这些值转换回数组 。const finalResult = [...mapOfUniqueObjects.values()];// finalResult:{id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie'},{id: 2, title: 'The Alchemist', author: 'Paulo Coelho'}结论
【object JavaScript选择 map而非对象存储键值对的 5 个理由附示例】如果需要存储键值对(散列或字典) , 请使用Map 。
如果你只使用基于字符串的键 , 并且需要最大的读取性能 , 那么对象可能是更好的选择 。
除此之外 , 用你想用的任何东西 , 因为 , 在一天结束的时候 , 这只是一个在互联网上随便一个人的文章 。
以下是我们介绍的内容: