Google Apps Script中如何按customer_profile_id从API数组提取followers_count
错误原因说明
- 你编写的嵌套map代码无法运行的核心原因是:
ex.dimensions是对象类型,不是数组,不存在map方法,调用后会直接报错 map方法的作用是对数组所有元素做统一转换,返回等长的新数组,不符合你「筛选指定ID对应数据」的需求,该场景应使用find(单条匹配)或filter(多条匹配)方法
可直接运行的实现代码
方案1:仅提取1111对应的粉丝数
// 查找customer_profile_id为1111的单条数据 const targetRecord = dataset.find(item => item.dimensions.customer_profile_id === 1111); // 提取粉丝数,添加兜底逻辑避免无匹配数据时报错 const facebookFollowerCount = targetRecord ? targetRecord.metrics['lifetime_snapshot.followers_count'] : 0; Logger.log(facebookFollowerCount); // 输出结果为407919
方案2:批量整理所有账号的粉丝数为映射对象
如果后续需要频繁调用不同ID的粉丝数,建议先将数组转换为ID:粉丝数的键值对对象,后续取值更方便:
const followerMap = dataset.reduce((result, current) => { const profileId = current.dimensions.customer_profile_id; const count = current.metrics['lifetime_snapshot.followers_count']; result[profileId] = count; return result; }, {}); // 直接通过ID取值即可 Logger.log(followerMap[1111]); // Facebook粉丝数:407919 Logger.log(followerMap[2222]); // Twitter粉丝数:1037310 Logger.log(followerMap[3333]); // Instagram粉丝数:806522
注意事项
- metrics里的字段名包含特殊字符,不能用
.语法访问,必须用方括号[]包裹字段名 - 如果存在同一个ID对应多条不同日期的数据的情况,可在
find的判断条件中补充日期筛选规则即可
内容的提问来源于stack exchange,提问作者racker
相关产品推荐
相关产品推荐

