DEV Community

Vladimir Schneider
Vladimir Schneider

Posted on • Updated on

normalize data without normalizr

Hi there 👋🏼

This is a short post about how normalize data using native available right now.

If you using a normalizr you know what I mean.

I've a simple server response data

const data = [
    { id: 1, name: 'Apple', type: 'fruit' },
    { id: 2, name: 'Orange', type: 'fruit' },
    { id: 3, name: 'Tomato', type: 'vegetable' },
];
Enter fullscreen mode Exit fullscreen mode

and I wanna get the entities and collection by attribute.

So, define it all.

const attribute = 'id';
const entities = [];
const collection = {};
Enter fullscreen mode Exit fullscreen mode

Next step will be iterate data and write

data.forEach((item) => {
    entities.push(item[attribute]);
    collection[attribute] = item;
});
Enter fullscreen mode Exit fullscreen mode

In final we have entities and collection and can handy to iterate and get date by iterable attribute.

Top comments (0)