如何用JavaScript筛选数组中无Instagram账号的联系人
解决方法:筛选无Instagram账号的联系人
首先,Array.filter()方法会遍历数组,返回所有满足回调函数条件的元素。要筛选没有Instagram账号的联系人,核心是判断每个联系人的social_media对象中是否不存在instagram属性。
完整代码实现
let contacts = [ { name: "Jane Doe", age: 21, social_media: { instagram: "jane.doe", twitter: "jane_doe" } }, { name: "John Doe", age: 21, social_media: { instagram: "john.doe", twitter: "john_doe" } }, { name: "Mary Deer", age: 21, social_media: { twitter: "mary_deer" } }, { name: "Gary Deer", age: 21, social_media: { twitter: "gary_deer" } } ] let noInstagram = contacts.filter(contact => { // 判断social_media对象中是否不存在instagram属性 return !('instagram' in contact.social_media); }); console.log(noInstagram); // 输出结果将包含Mary Deer和Gary Deer的对象
关键逻辑说明
- 使用
'instagram' in contact.social_media可以精准检查对象是否包含指定属性,返回布尔值 - 前缀
!对结果取反,代表不包含该属性的情况,正好匹配我们筛选无Instagram账号的需求 filter()会自动收集所有回调函数返回true的元素,最终存入noInstagram变量
你之前的代码存在两个问题:
filter的回调函数需要返回布尔值,而非仅执行console.log- 缺少正确的属性存在性判断逻辑
内容的提问来源于stack exchange,提问作者A.C. Belaire
相关产品推荐
相关产品推荐

