I'm trying to figure out how to structure data that allows for easy and quick retrieval when given a lookup ID. There are two methods I'm considering:
METHOD 1: An object of objects where each key is a lookup ID
const people1 = {
    1: {
        name: 'bob',
        weight: 180
    },
    25: {
        name: 'chris',
        gender: 'male'
    },
    127: {
        name: 'shannon',
        age: 43
    },
}This method, in my opinion, offers the easiest way to lookup a person...
console.log(people1[127])
// {name: "shannon", age: 43}... but I don't know if it's the best. My worries are:
- I feel like objects are meant to contain information regarding one singular thing and arrays are meant for a collection of things. In this case, I guess the people could be considered a single user-base?
- Reordering items would be difficult. I'm trying to use this data in a Vuejs app which uses v-forto display people. In order to use this, I would probably have to have agetterthat converts the object into an iterable list.
- Related to point above, it's difficult to iterate over this.
METHOD 2: An array of objects where the lookup ID is stored as a property in each object
const people2 = [
    {
        id: 1,
        name: 'bob',
        weight: 180
    },
    {
        id: 25,
        name: 'chris',
        gender: 'male'
    },
    {
        id: 127,
        name: 'shannon',
        age: 43
    },
]Using this method, there are many ways I can think of that allows for data retrieval. You can see a StackOverflow discussion on these different options here.
// Using .find()
console.log(people2.find(person => person.id === 127));
// {id: 127, name: "shannon", age: 43}
// Using .forEach()
people2.forEach((person) => {
    if (person.id === 127) {
        console.log(person);
    }
});
// {id: 127, name: "shannon", age: 43}
// Using for loop
for (var i = 0; i < people2.length; i++) { 
    if (people2[i].id === 127) { 
      console.log(people2[i]);
      break;
    } 
  }
// {id: 127, name: "shannon", age: 43}
// Using .filter()
console.log(people2.filter((person) => {return person.id === 127})[0]);
// {id: 127, name: "shannon", age: 43}My worries here are:
- Finding a person on a lookup ID is not as easy as the first option. I know I can make a function and use that, but I feel like that wouldn't be best performance-wise compared to method 1.
- As stated above, I am trying to use this in a Vuejs store. If I want to mutate a person, each of my mutations would have to find the person first which would call for repeated code. I could use a function, but it would have to be imported into my vuex store or above my vuex instance since I can't call a getter inside a mutation.
