首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取数据并向Json对象添加标题

获取数据并向Json对象添加标题
EN

Stack Overflow用户
提问于 2019-05-28 02:11:20
回答 2查看 496关注 0票数 0

我想将标题添加到我的JSON对象中,我希望实现的结构是:

{
"posts": [
    {
        "title": "put title here",
        "upvotes": 1234,
        "score": 1000,
        "num_comments": 100,
        "created": "16.05.2019 12:12",
    },
]
}

我能够获取数据并将其放入26个元素的数组中,一切都很好,但我希望以某种方式添加这个“帖子”:为了超越整个rest,以下是我的代码:

fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
   let posts = await res.data.children.map(el => {
    let title = el.data.title;
    let upvote = el.data.ups;
    let score = el.data.score;
    let comments = el.data.num_comments;
    let created = el.data.created;
    const allPosts = {title, upvote, score, comments, created}
    postList.push(allPosts)
    return postList
})  
console.log(posts);

    return posts    
})
EN

回答 2

Stack Overflow用户

发布于 2019-05-28 02:33:18

  fetch("https://www.reddit.com/r/funny.json")
  .then(resp => resp.json())
  .then(async res => {
    console.log(res);
    let posts = await res.data.children.map(el => {
      let title = el.data.title;
      let upvote = el.data.ups;
      let score = el.data.score;
      let comments = el.data.num_comments;
      let created = el.data.created;
      const allPosts = { title, upvote, score, comments, created };
      let postList = [];
      postList.push(allPosts);
      return postList;
    });
    console.log({"posts": posts});

    return {"posts": posts};
  });
票数 1
EN

Stack Overflow用户

发布于 2019-05-28 02:19:52

您可以尝试以下代码。

fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(res => ({
  posts: res.data.children.map(el => ({
    title: el.data.title,
    upvote: el.data.upvote,
    score: el.data.score,
    comments: el.data.num_comments,
    created: el.data.created
  }))
}))
.then(posts => {
  console.log(posts);
});

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56330695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档