首页 > 解决方案 > 如何使一个数组的属性成为另一个数组的属性(代码优化)

问题描述

这就是我所拥有的

const users = [
    { id: 1, name: 'Mike', postIds: [11, 22] },
    { id: 2, name: 'Dan', postIds: [33] },
    { id: 3, name: 'Lance', postIds: [44] },
];

const posts = [
    { id: 11, title: 'How good is he' },
    { id: 22, title: 'How fast is he' },
    { id: 33, title: 'How to make it faster' },
    { id: 44, title: 'How can he do it' },
];

这就是我需要在输出中得到的

const expectedResult = [
  {
    id: 1,
    name: 'Mike',
    posts: [
      { id: 11, title: 'How good is he' },
      { id: 22, title: 'How fast is he' },
    ]
  },
  {
    id: 2,
    name: 'Dan',
    posts: [{ id: 33, title: 'How to make it faster' }]
  },
  {
    id: 3,
    name: 'Lance',
    posts: [{ id: 44, title: 'How can he do it' }]
  },
]

这就是我尝试过的。它有效,但它很愚蠢,我认为它可以在一次操作中完成。请检查我能做些什么使它更干净

const users = [
    { id: 1, name: 'Mike', postIds: [11, 22] },
    { id: 2, name: 'Dan', postIds: [33] },
    { id: 3, name: 'Lance', postIds: [44] },
];

const posts = [
    { id: 11, title: 'How good is he' },
    { id: 22, title: 'How fast is he' },
    { id: 33, title: 'How to make it faster' },
    { id: 44, title: 'How can he do it' },
];

let updUsers = users.map(obj => ({ ...obj,
  posts: [...posts]
}))
const output = updUsers.map(
  user => ({
    ...user,
    posts: user.posts.filter(
      post => user.postIds.includes(post.id)
    )
  })
);
const expectedOut = output.map(({
  id,
  name,
  posts
}) => ({
  id,
  name,
  posts
}))
console.log(expOut)

标签: javascriptecmascript-6destructuring

解决方案


posts您可以在映射时进行过滤,users而不是将其作为第二遍进行。

const users = [
    { id: 1, name: 'Mike', postIds: [11, 22] },
    { id: 2, name: 'Dan', postIds: [33] },
    { id: 3, name: 'Lance', postIds: [44] },
];

const posts = [
    { id: 11, title: 'How good is he' },
    { id: 22, title: 'How fast is he' },
    { id: 33, title: 'How to make it faster' },
    { id: 44, title: 'How can he do it' },
];

let expOut = users.map(({id, name, postIds}) => ({ id, name,
  posts: posts.filter(({id}) => postIds.includes(id))
}))

console.log(expOut)


推荐阅读