【发布时间】:2019-04-10 06:21:08
【问题描述】:
当我获取 api json 数据时,我得到双倍的结果。使用.forEach() 方法,我将双重数据打印到我只需要一组的HTML 中。
这是我的 api 调用和循环
var url = 'https://api.myjson.com/bins/1geede';
fetch(url)
.then(response => response.json())
.then(data => {
const scope = data.data.messages;
console.log(scope);
//Looping through the user data
scope.forEach((i) => {
let user = i;
if (user.username == "Mygel van Trabel") {
user1( user.focused, user.message, getTimeStamp(user.timestamp), user.username);
} else {
user2( user.focused, user.message, getTimeStamp(user.timestamp), user.username);
}
});
}).catch( error => console.error(error));
User1 和 User2 是函数。以下是来自console.log(scope) 的结果:
VM app.js:20 (4) [{…}, {…}, {…}, {…}]
app.js:20 (4) [{…}, {…}, {…}, {…}]
现在它正在将两个集合都打印到 DOM 中,而我只需要一个。为什么会这样?
下面的图片是我想要完成的。
这张照片是它现在给我的结果
【问题讨论】:
-
user1和user2函数是什么?没有它也可以正常工作:jsfiddle.net/bvsLueky -
我刚刚将它们添加到帖子中
-
看起来他们没有记录任何东西,但是没有它们,正如您从小提琴中看到的那样,数据不会重复(例如显示 4 个项目,而不是 8 个)。你能展示演示minimal reproducible example的代码吗?
-
@CertainPerformance 怎么样?
-
您能否检查您的网络选项卡以确认该请求仅发送 1 次,并且 edit 您的帖子中包含此信息?这是重复记录最常见的情况
标签: javascript json api foreach