0

I have an array of objects (comments added by users):

const myArray = [
  {
    "text": "Hello",
    "id": "11",
    "$type": "Comment"
  },
  {
    "text": "Date of birth: 01-01-2022",
    "id": "22",
    "$type": "Comment"
  },
  {
    "text": "lalala",
    "id": "33",
    "$type": "Comment"
  }
];

My goal is:

  1. find object, which string field text includes a phrase Date of birth
  2. find value of id field in this object

I tried this:

let dateOfBirthComment = myArray.find(element => element.text.includes('Date of birth'));

let dateOfBirthCommentId = dateOfBirthComment.id;

console.log(dateOfBirthCommentId);

When executing code above I get an error:

Error: Cannot read properties of null (reading 'includes')

Unfortunately, I can't use this:

let dateOfBirthComment = array.find(element => element.text === 'Date of birth: 01-01-2022');

Because date can be absolutely random in different cases.

Solution seems to be easy, but I'm quite new in JS and I'm really stuck. Could you please help me?

  • That means `text` is `null` in some of those objects. Either filter those beforehand or use [Optional chaining](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – Sebastian Simon Dec 09 '22 at 14:11
  • Your *provided* code works fine: https://jsfiddle.net/uhev8aqL/ - it fails if your have a missing/null text value *before* the one that matches. – freedomn-m Dec 09 '22 at 14:12
  • use `Optional chaining(?.)`. No error show, if some object doesn't have text – Anil kumar Dec 09 '22 at 14:14

0 Answers0