DEV Community

loading...

How to do you store items with unique id ?

prog profile image prog ・1 min read

Let's imagine we want a list of object that contains an unique id for each item.

Which format/way of storing data is the best in the long term ? (data1 or data2)

type itemType = {
    name: string;
    age: number;
};

const data1: Record<number, itemType> = {
    1: {
        name: 'foo',
        age: 14,
    },
    2: {
        name: 'fee',
        age: 16,
    },
};

// --- OR ---

const data2: (itemType & { id: number })[] = [
    {
        id: 0,
        name: 'foo',
        age: 14,
    },
    {
        id: 1,
        name: 'fee',
        age: 16,
    },
];
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
seanperkins profile image
Sean Perkins

You'll find in software, the "best" is always subjective.

In your first example, the benefits are around a key structure that is numerically organized, most likely pre-sorted (assumptive based on the current data). You also get lint-protection against duplicate ids. The downsides are that you will have to access the numeric id based on the key, not directly from the object itself. You'll see this pattern in many key-document stores (i.e. Firebase/LevelDB). A common practice is having the id on the object as well, for ease-of-access. The object itself is not directly iterable, requiring usage of something like Object.keys to loop through results.

In the second example, you have the benefits of the array prototype (built in functions) as well as many of the operator functions accept an array instead of an object, but you can obviously mutate the object itself into an array easily. You can also easily re-sort the collection by any property and have the same representation of the data (id, name and age). You lose out on the built in lint protection for duplicate identifiers, so you would to manage that yourself.

In my own preference, I'd typically structure my data like your second example. Although I would avoid a numeric id (outside of a database table). I would lean into unique generated ids, such as the uuid package. Data representation is often fluid, and there are plenty of instances where I would have two separate functions to access the data in either representation, based on either convenience or performance.

Collapse
prog profile image
prog Author • Edited

Ok, thank you for your reply. Now, I know I'm not the only one to face this dilemma. 😀
I'll go for the data2 version even though it's the least efficient and slower (reference)[stackoverflow.com/questions/172950...)