'Storage list of contacts by first letter index

I'm making a contact list ordered alphabetically, the way that I'm currently storing is inside an object like this:

{
  "&": [
    {
      "key": "20444358",
      "initials": "@#",
      "name": "@name #"
    },
    {
      "key": "20444669",
      "initials": "@@",
      "name": "@ @"
    }
  ],
  "#": [
    {
      "key": "4419686",
      "initials": "1",
      "name": "1075621114"
    },
    {
      "key": "41604990",
      "initials": "12",
      "name": "123 Test 23"
    },
    {
      "key": "32783347",
      "initials": "2",
      "name": "232323"
    }
  ],
  "A": [
    {
      "key": "20444317",
      "initials": "AJ",
      "name": "Àbdon Jua"
    },
    {
      "key": "20444454",
      "initials": "AA",
      "name": "Abraão Moura"
    }
  ]
}

I'm facing two problems at the moment:

  1. When I fetch a new page of contacts and need to merge them with the current object I'm doing like this: contacts = {...contacts, ...newContacts}
  2. I'm rendering them on a FlatList, and having a hard time getting the Index.

This is my fetch:

if (response.data !== []) {
  for (let i = 0; i < response.data.length; i++) {
    let indexInitial = getIndexInitial(response.data[i].name)
    if (!(indexInitial in newContacts)) {
      newContacts[indexInitial] = [{
        key: response.data[i].id.toString(),
        initials: getInitials(response.data[i].name),
        name: response.data[i].name
      }]
    } else {
      newContacts[indexInitial].push({
        key: response.data[i].id.toString(),
        initials: getInitials(response.data[i].name),
        name: response.data[i].name
      })
    }
  }
  pushContacts(newContacts);
  page.current = currentPage + 1;
} else {
  setEndOfTheList(true)
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source