如何从cartItem数组中查找与findIt匹配的对象?
问题:从购物车数组中匹配指定商品及属性对象
需要从cartItem数组中找出与findIt的productId和attribute属性完全匹配的对象,给定的定义如下:
const findIt = { productId: "htm-45", attribute: [ {name:"size",index:2}, {color:"red",index:2} ] } const cartItem = [ { productId: "htm-45-34", atrributeId:"_672349e", attribute: [ {name:"size",index:1} ] }, { productId: "htm-45", attribute: [ {name:"size",index:2}, {name:"size",index:3}, ] }, { productId: "htm-45", attribute: [ {name:"size",index:2}, {color:"red",index:2} ] } ]
实现方案
数组和对象属于引用类型,无法直接用全等运算符(===)判断匹配,需要自定义比较逻辑,具体实现如下:
1. 编写属性数组匹配函数
先实现辅助函数,判断两个attribute数组是否完全一致(包括数组长度、每个元素的所有键值对):
function isAttributesMatch(targetAttrs, itemAttrs) { // 先判断数组长度是否一致 if (targetAttrs.length !== itemAttrs.length) return false; // 遍历每个属性对象,比较所有键值对 return targetAttrs.every((targetAttr, index) => { const itemAttr = itemAttrs[index]; // 获取两个对象的所有键,判断键的数量和内容是否一致 const targetKeys = Object.keys(targetAttr); const itemKeys = Object.keys(itemAttr); if (targetKeys.length !== itemKeys.length) return false; // 逐个比较键值对 return targetKeys.every(key => targetAttr[key] === itemAttr[key]); }); }
2. 查找匹配的购物车项
使用数组find方法,结合辅助函数筛选符合条件的对象:
const matchedItem = cartItem.find(item => { // 先匹配productId,快速排除不匹配项 if (item.productId !== findIt.productId) return false; // 再匹配attribute数组 return isAttributesMatch(findIt.attribute, item.attribute); }); console.log(matchedItem); // 输出结果: // { // productId: "htm-45", // attribute: [ // {name:"size",index:2}, // {color:"red",index:2} // ] // }
逻辑说明
- 优先通过
productId过滤,减少后续比较的工作量 - 对
attribute数组先校验长度,长度不一致直接排除 - 对每个属性对象,校验键的数量和对应的值,确保所有键值对完全匹配
内容的提问来源于stack exchange,提问作者Tanver shikder 172 636
相关产品推荐
相关产品推荐

