如何过滤API返回对象中重复的center属性值?
如何过滤NASA接口返回结果中重复的center属性值?
嘿,我来帮你搞定这个重复值过滤的问题!你调用NASA接口拿到的485个对象里,有些center属性值重复,咱们可以用几种简单的方式来处理,具体看你是需要仅保留去重后的center字符串列表,还是保留每个唯一center对应的完整对象(只留第一个出现的实例)。
先结合你的现有代码,我们在处理返回数据的环节加入去重逻辑:
方法1:获取去重后的center字符串数组
如果你的需求只是拿到所有不重复的center名称,用Set来处理最方便——因为Set本身就会自动剔除重复值:
function call() { fetch('https://data.nasa.gov/resource/9g7e-7hzz.json') .then((response) => response.json()) .then((data) => { // 提取所有center值,并用Set去重后转成数组 const uniqueCenters = [...new Set(data.map(item => item.center))]; getLocations(uniqueCenters); // 这里传给getLocations的是去重后的字符串数组 }) } // 假设你的getLocations是用来处理数据的函数 function getLocations(locations) { // 示例:打印去重结果 console.log("去重后的center列表:", locations); }
方法2:保留完整对象,仅保留每个center的第一个实例
如果需要保留每个对象的完整信息,但每个center只留第一次出现的那个对象,可以结合Set和filter方法:
function call() { fetch('https://data.nasa.gov/resource/9g7e-7hzz.json') .then((response) => response.json()) .then((data) => { const seenCenters = new Set(); // 过滤数组,只保留未出现过的center对应的对象 const uniqueLocationObjects = data.filter(item => { // 额外判断:避免无center属性的对象导致undefined重复 const centerValue = item.center ?? ''; if (!seenCenters.has(centerValue)) { seenCenters.add(centerValue); return true; } return false; }); getLocations(uniqueLocationObjects); // 这里传给函数的是去重后的对象数组 }) } function getLocations(locations) { console.log("去重后的对象数组:", locations); }
补充小提示
如果需要保留最后出现的某个center对应的对象,可以把filter换成reduce来手动构建结果:
const uniqueLocationObjects = data.reduce((acc, item) => { const centerValue = item.center ?? ''; acc[centerValue] = item; // 后面的对象会覆盖前面的 return acc; }, {}); // 再转成数组:Object.values(uniqueLocationObjects)
内容的提问来源于stack exchange,提问作者Giesburts
相关产品推荐
相关产品推荐

