Home > Back-end >  Conditioning inside array.map() objects
Conditioning inside array.map() objects

Time:11-05

I'm trying to join three array's based on matching id's, but if the posts or likes is "undefined", then it ends up breaking the code, how would I apply conditioning to this, if the array is undefined, it should return empty and if not the filtering should take place.

//sample data
const posts = 
  [ { _id: 1
    , message: 'this is post one'
    , likes:    [ { _id: 1111 } , { _id: 2222 } ] 
    , comments: [ { _id: 3333 } , { _id: 4444 } ] 
    } 
  ] 
const comments = 
  [ { _id: 3333, message: 'this is comment 1' } 
  , { _id: 4444, message: 'this is comment 2' } 
  ] 
const likes = 
  [ { _id: 1111, user: 'Peter' } 
  , { _id: 2222, user: 'John'  } 
  ] 


      const newPosts = posts.map(post => ({
        ...post,
        likes: likes.filter(like => post.likes.map(like => like._id).includes(like._id)),
        comments: comments.filter(comment => post.comments.map(comment => comment._id).includes(comment._id)),
      }))

what I've tried

const newPosts = posts.map(post => ({
          ...post,
          likes: likes.filter(like => like === undefined ? '': post.likes.map(likes => likes._id).includes(like._id)),
          comments: comments.filter(comment => comment === undefined ? '': post.comments.map(comments => comments._id).includes(comment._id)),
        }))

the use for this is socket.io emits changes from my database with the three different sockets, I'm able to grab all three arrays containing the changes and join them into one updated array "posts" by matching ID's, so meaning the comments/likes array can end up being empty from time to time, there by I'd like to apply conditioning that it will check whether it is undefined or not. If it's undefined it should just return the value of an empty array else the filter() action should occur, would this be possible, I've been stuck on this for a bit, so any help would be really appreciated.

CodePudding user response:

Try this:

const posts = [{
  _id: 1,
  message: 'this is post one',
  likes: [{
    _id: 1111
  }, {
    _id: 2222
  }],
  comments: [{
    _id: 3333
  }, {
    _id: 4444
  }]
}];

const comments = [{
  _id: 3333,
  message: 'this is comment 1'
}, {
  _id: 4444,
  message: 'this is comment 2'
}];

const likes = [{
  _id: 1111,
  user: 'Peter'
}, {
  _id: 2222,
  user: 'John'
}];

const newPosts = posts.map((post = {}) => ({
  ...post,
  likes: likes.filter((like = {}) =>
    post.likes.find((likeItem = {}) => likeItem._id === like._id)
  ).map(like => like._id),
  comments: comments.filter((comment = {}) =>
    post.comments.find((commentItem = {}) => commentItem._id === comment._id)
  ).map(comment => comment._id),
}));

console.log(newPosts);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related