mongoose 如何用javascript将两个id匹配的对象中的一些元素复制到一个对象中

5f0d552i  于 2023-01-26  发布在  Go
关注(0)|答案(1)|浏览(117)

我有一个发布者对象数组和一个由这些发布者创建的创意对象数组。每个创意对象都包含一个带有发布者ID的"user:"键。我需要获取每个创意对象并添加发布者的用户名,以便它同时具有发布者的ID用户名。换句话说,我只从每个对象中获取某些元素,并创建一个新的对象数组。
示例:

const publisherObjects = [
  {
    username: 'Curtis',
    description: 'description',
    email: 'email@email.com'
    id: '111'
  }, {
  ...
  }
]

以及

const ideaObjects = [
  {
    title: 'new idea',
    thesis: 'this is my idea',
    user: '111'
  }, {
  ...
  }
]

变成

const ideasWithUsernames = [
  {
    title: 'new idea',
    thesis: 'this is my idea',
    user: '111',
    username: 'Curtis'
  }, {
  ...
  }
]

我试过这个:

let ideas = ideaObjects.map(i => {
  let publisher = publisherObjects.find(p => p._id === i.user)
  if (publisher)
     return {
        id: i._id,
        title: i.title,
        thesis: i.thesis,
        ticker: i.ticker,
        longOrShort: i.longOrShort,
        publisher: {
          id: i.user,
          username: p.username
        }
     }
}

我希望它返回一个如上所述的对象数组,但是我得到了一个"undefined"数组。

[
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

任何帮助都将不胜感激。

ffvjumwh

ffvjumwh1#

好像有用。这是你想要的吗?

const publisherObjects = [
    {
        username: 'Curtis',
        description: 'description',
        email: 'email@email.com',
        id: '111',
    },
]

const ideaObjects = [
    {
        id: '123',
        title: 'new idea',
        thesis: 'this is my idea',
        ticker: 'foo',
        longOrShort: 'bar',
        user: '111',
    },
]

let ideas = ideaObjects.map(ideaObj => {
    let publisher = publisherObjects.find(p => p.id === ideaObj.user)
    if (!publisher) return null;
    let newIdeaObj = {
        ...ideaObj,
        publisher: {
            id: ideaObj.user,
            username: publisher.username,
        }
    }
    delete newIdeaObj.user;
    return newIdeaObj;
})

console.log(ideas);

相关问题