You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:57:04