Object(Old good javascript object)
Pretty common scenario - when you have list of objects came from API:
const users = [
{id:'123', name: 'Moshe'},
{id:'124', name: 'Vasia'},
]
and you need to access one of the objects by its 'id' - you can do it by searching through the array, like this:
const currentUser = users.find(({id}) => id === '123');
But, of course, if you have array with lot of users - it will be much quicker to access some certain user by id - if "users" were stored inside Object with following structure:
const users = {
'123': {id:'123', name: 'Moshe'},
'124': {id:'124', name: 'Vasia'},
}
const currentUser = users['123'];
BTW, for optimize your performance you can restructure the users collection from array to object using following code:
let optimizedUsers = users.reduce((acc, user) => {
return {
...acc,
[user.id]: user
};
}, {});
const currenttUser = optimizedUsers['123'];
console.log(currenttUser.name); // will print "Moshe"
You just saw the scenario with advantage of using Object upon Array
No comments:
Post a Comment