0

I have a simple photo categories array that looks like this:

[
  {
    category: 1001,
    photos: [
      { id: 100101, url: 'url.com/100101', favorite: false},
      { id: 100102, url: 'url.com/100102', favorite: false}
    ]
  },
  {
    category: 1002,
    photos: [
      { id: 100201, url: 'url.com/100201', favorite: false},
      { id: 100202, url: 'url.com/100202', favorite: false}
    ]
  }
]

If I favorite photoId 100201, how can I update my array so that 100201 is updated to favorite: true? I am trying to look at lodash documentation but I am not sure what I should be looking for.

Thanks

user1354934
  • 8,139
  • 15
  • 50
  • 80

1 Answers1

0

Let's say that this array is stored in a variable named categories, and assuming (based on the data you provided) that each photo id starts with the exact category id, then:

function inCategory(category: string, id: string): boolean {
    return id.substring(0, category.length) === category;
}

function favorite(photoId: number): void {
    for (let i = 0; i < categories.length; i++) {
        if (inCategory(categories[i].category.toString(), photoId.toString())) {
            for (let j = 0; j < categories[i].photos.length; j++) {
                if (categories[i].photos[j].id === photoId) {
                    categories[i].photos[j].favorite = true;
                }
            }
        }
    }
}

(code in playground)

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299