Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access array item by property value and then update it's value?

I have an array of object that looks like this:

const tickets = 
[
  {
    ticketId: 'aaa',
    authorId: 'abc',
    replyCount: 0,
    status: 'Open',
    threads: [
      {
        threadId: 'abc',
        authorId: 'abc',
        direction: 'in',
        content: 'blah blah blahh'
      },
    ],
  },
  {
    ticketId: 'bbb',
    authorId: 'efg',
    replyCount: 0,
    status: 'Open',
    threads: [
      {
        threadId: 'efg',
        authorId: 'efg',
        direction: 'in',
        content: 'blah blah blahh'
      },
    ],
  },
  .......
]

Now I want to access the array item where ticketId equals aaa and change it’s threads property.

I have tried doing using tickets['aaa'].threads = [ ... ] but it throws these errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Eslint: Unsafe member access .threads on an 'any' value

TypeScript: Element implicitly has an 'any' type because index expression is not of type 'number'

>Solution :

Find the index where ticketId equals "aaa"

tickets[tickets.findIndex(v => v.ticketId === "aaa")].threads = [/* ... */];

With index validation:

const idx = tickets.findIndex(v => v.ticketId === "aaa");
if (idx > -1) tickets[idx].threads = [/* ... */];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading