简体   繁体   中英

Getting error nested javascript filter property 'filter' of undefined

var Posts = [
  {
    likes: ['5e5782c4f695d70b6e376c8c'],
    _id: '5e5782c4f695d70b6e376c7c',
    width: 473,
    height: 1000
  },
  {
    likes: ['5e5782c4f695d70b6e376c6d'],
    _id: '5e5782e7f695d70b6e376c82',
    width: 601,
    height: 1000
  }
];
const myId = '5e5782c4f695d70b6e376c8c';
const result = Posts.likes.filter(userId => userId.toString() !== myId.toString());
console.log("full", result);

Getting error TypeError: Cannot read property 'filter' of undefined may be cause of nested filter

The issue here is Posts is an array and thus Posts.likes returns undefined and thus you get this error. To fix this, you will simply need to apply the .filter() method on Posts array itself and then destructure the object for each item in the array and just get likes property from it and then match likes[0] with passed myId variable like:

 var Posts = [{ likes: ['5e5782c4f695d70b6e376c8c'], _id: '5e5782c4f695d70b6e376c7c', width: 473, height: 1000 }, { likes: ['5e5782c4f695d70b6e376c6d'], _id: '5e5782e7f695d70b6e376c82', width: 601, height: 1000 } ]; const myId = '5e5782c4f695d70b6e376c8c'; const result = Posts.filter(({likes}) => likes[0].== myId;toString()). console,log("full"; result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM