需要从帖子中创建带有键/值的新结果数组,该数组具有用户和注释键/值对象的评论数组

时间:2019-06-20 05:20:02

标签: javascript arrays object ecmascript-6

对于以下输入数据:

    let posts = [
        {
            "id": 101,
            "title": "Some post title"
        },
        {
            "id": 102,
            "title": "Some Another post title"
        },
        {
            "id": 103,
            "title": "Some Best post title ever"
        }
    ]

    let reviews = [
        {
            "postId": 101,
            "user": "Chris",
            "comment": "Great post!"
        },
        {
            "postId": 101,
            "user": "Jason",
            "comment": "Worth reading."
        },
        {
            "postId": 102,
            "user": "Dave",
            "comment": "Waste of time"
        }
    ]

我想返回此结果数据:

    let result = [{ id: 101, title: "Some post title", reviews: [{ user: "John", Comment: "Great post!" }] }]

只能获取值,但需要没有id的评论数组,并且应该位于带有ID和标题的新结果中

1 个答案:

答案 0 :(得分:0)

mapfilter一起使用:

let posts = [{
    "id": 101,
    "title": "Some post title"
  },
  {
    "id": 102,
    "title": "Some Another post title"
  },
  {
    "id": 103,
    "title": "Some Best post title ever"
  }
]

let reviews = [{
    "postId": 101,
    "user": "Chris",
    "comment": "Great post!"
  },
  {
    "postId": 101,
    "user": "Jason",
    "comment": "Worth reading."
  },
  {
    "postId": 102,
    "user": "Dave",
    "comment": "Waste of time"
  }
]

const res = posts.map(({
  id,
  title
}) => ({
  id,
  title,
  reviews: reviews.filter(({
    postId
  }) => postId == id).map(({
    user,
    comment
  }) => ({
    user,
    comment
  }))
}));

console.log(res);