Array map returning an array of undefined values ​​- JavaScript – SitePoint Forums

0

So I use the following data as an example

const bios = [
  {users:
    [
      {name: "Tim Blackburn", bio: "Tim is an avid...", image: "./images/tim-blackburn.jpg" },
      // Exclude: Faculty_Bio-Photoholder
      {name: "Greg Fortner", bio: "Greg likes kites...", image: "./images/Faculty_Bio-Photoholder.jpg" }, 
      {name: "Sally Brown", bio: "Sally is a martial artist...", image: "./images/sally-brown.jpg" },
      {name: "John Smith", bio: "John likes to fish...", image: "./images/john-smith.jpg" },
      {name: "Alice Evans", bio: "Alice likes poetry...", image: "./images/alice-evans.jpg" }, 
    ]
  }
];

const titles = [
  {users:
    [
      {name: "Tim Blackburn", title: "Assistant Professor of Chemistry" },
      {name: "Greg Fortner", title: "Director of Academic Affairs"},
      {name: "Sally Brown", title: "Headmistress" },
      // Exclude: no title
      {name: "John Smith" }
      // Exclude: no entry for Alice
    ]
  }
];

My code is similar to yours, other than that I check the title in the Array.find callback

function getFacultyUsers(userBios, userTitles) {

  return userBios.map((userBio) => {
    const targetName = userBio.name;

    const foundUser = (
      userTitles.find(
        // destructure name and title
        ({ name, title }) => {
          return name === targetName && title !== undefined;
        }
      )
    );
    
    // no match return 'userBio' as is
    if (foundUser === undefined) return userBio;
    
    const image = userBio.image;
    
    // no image or the image includes 'Faculty_Bio-Photoholder.jpg' return 'userBio' as is.
    if (image === undefined || image.includes('Faculty_Bio-Photoholder.jpg')) {
      return userBio;
    }
    
    // match ticks all boxes return with title
    return { ...userBio, title: foundUser.title }
  })
}

i call it that

const userBios = bios[0].users;
const userTitles = titles[0].users;
  
const users = getFacultyUsers(userBios, userTitles);

The output I get is

[
  {
    "name": "Tim Blackburn",
    "bio": "Tim is an avid...",
    "image": "./images/tim-blackburn.jpg",
    "title": "Assistant Professor of Chemistry"
  },
  {
    "name": "Greg Fortner",
    "bio": "Greg likes kites...",
    "image": "./images/Faculty_Bio-Photoholder.jpg"
  },
  {
    "name": "Sally Brown",
    "bio": "Sally is a martial artist...",
    "image": "./images/sally-brown.jpg",
    "title": "Headmistress"
  },
  {
    "name": "John Smith",
    "bio": "John likes to fish...",
    "image": "./images/john-smith.jpg"
  },
  {
    "name": "Alice Evans",
    "bio": "Alice likes poetry...",
    "image": "./images/alice-evans.jpg"
  }
]

Running your code gives the same result.

  1. What is the solution?
  2. What should be the expected result?
  3. Are the source data bios, titles correct?
Share.

Comments are closed.