javascript - 比较对象数组并返回不在其中一个数组中的新对象数组
问题描述
我一直无法弄清楚如何让它发挥作用。
基本上,我有两个数组。这些数组将包含对象。
第一个数组是包含用户喜爱电台的对象数组。
第二个数组是包含需要移除的站点的对象数组。
我想比较第一个和第二个数组,并返回一个新数组,其中包含不在删除站数组中的站...
例如...
const favourites = [{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }, { station_name: 'Connel Ferry', crs_code: 'CON' }, { station_name: 'Oban', crs_code: 'OBN' }]
const toBeRemoved = [{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }]
然后,我希望返回一个包含其他 2 个站点的数组...
我花了几个小时试图弄清楚如何做到这一点,但似乎不起作用!
TIA
解决方案
以下代码演示了具有相同属性的两个对象可能不相等:
const ob_1={color:'black', size:'big'},
ob_2={color:'black', size:'big'};
console.log(ob_1==ob_2); // false
所以我们需要经常进行深度比较:
const favourites = [
{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' },
{ station_name: 'Connel Ferry', crs_code: 'CON' },
{ station_name: 'Oban', crs_code: 'OBN' }
];
const toBeRemoved = [
{ station_name: 'Kyle of Lochalsh', crs_code: 'KYL' }
];
console.log(
// Array.filter applies our custom function to each item in the
// `favourites` array and returns a new (smaller) array containing
// all items for which our custom function returns true
favourites.filter(
// Our custom function (using "arrow function" syntax) takes
// a station object and uses `Array.some` to compare it to each
// item in the `toBeRemoved` array. Our custom function returns
// true if the current station is not in `toBeRemoved`.
(station) =>
// Array.some takes another custom function which is applied
// to each item in `toBeRemoved`, returning true if this
// custom function returns true for at least one item
!toBeRemoved.some(
// This custom function takes a station object (called `st`)
// and "deeply" compares each property against the same
// property in the current station of the `favorites`
// array, returning true if both properties match
(st) =>
st.station_name == station.station_name &&
st.crs_code == station.crs_code
)
)
);
推荐阅读
- node.js - 无法导出连接
- reactjs - ReactNative Expo 预加载和缓存图像
- python - Python - 按组列出来自日志和输出的数据并计算总数
- powerbi - 表格模型 - 按列排序:属性值无效的多个不同值
- c++ - 内部带有数字的动态 ASCII 框
- angular - errors.ts:30 错误错误:未捕获(在承诺中):错误:无法匹配任何路由。URL 段:'产品,%20productId'
- javascript - 根据jQuery中的函数参数创建一个显示所选属性和值的文本的函数
- python - Python从之前的两个类中继承一个类(机器学习预处理)
- java - Spring-security:有没有办法使用来自客户端的 cookie 验证 url 参数?
- python - Lambda Python 查询 SSM 参数存储值