Angular使用difference()对比对象数组后无法通过点语法获取url键值
问题原因
difference() 函数的返回值为数组类型,而非单个对象。你当前场景下差集虽然仅包含1个Steam Store对应的对象,但该对象依然被包裹在数组结构中,直接对数组调用.url属性不存在,因此操作失败。
正确写法
确定差集仅1个元素时,直接取首元素读取属性
const storesDifference = difference(result, this.stores); console.log('difference', storesDifference[0].url);
提取所有差集对象的url组成纯链接数组(符合你的需求)
const storesDifference = difference(result, this.stores); const diffUrlList = storesDifference.map(item => item.url); // 最终diffUrlList输出为 ["https://store.steampowered.com"]
注意事项
- 如果你使用的是 Lodash 等工具库的基础
difference()方法,默认执行全等===对比,对比对象数组时如果两个对象不是完全相同的引用,会出现差集判断错误的问题。需要按对象属性对比时,请使用支持自定义对比规则的方法,示例:
// 以Lodash为例,使用differenceWith + isEqual实现对象属性深度对比 import { differenceWith, isEqual } from 'lodash'; const storesDifference = differenceWith(result, this.stores, isEqual);
内容的提问来源于stack exchange,提问作者Rihards Ādminis
相关产品推荐
相关产品推荐

