Home > Net >  How to copy some elements from two objects with matching ids into one object with javascript
How to copy some elements from two objects with matching ids into one object with javascript

Time:01-25

I have one array of publisher objects and one array of idea objects that were created by those publishers. Each idea object contains a 'user:' key with the publisher's Id. I need to take each of the idea objects and add the publisher's username, so that it will have both the publisher's Id and username. In other words, I'm taking only certain elements from each object and creating a new array of objects.

Example:

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

and


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

into


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

I have tried this:

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
        }
     }
} 

I expected this to return an array of objects like above, however instead I get an array of 'undefined'.

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

Any help would be greatly appreciated.

CodePudding user response:

This seems to work. Is this what you want?

const publisherObjects = [
    {
        username: 'Curtis',
        description: 'description',
        email: '[email protected]',
        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);

  • Related