Twitter: @jacobmgevans
I wrote out some examples of Object methods being used, to get certain data from the objects you feed into them.
const starTrekNexGen = {
Captain: 'Jean Luc Picard',
ExecutiveOfficer: 'Riker',
HeadOfSecurityWeaponsOfficer: 'Worf',
ChiefMedicalOfficer: 'Beverly Crusher',
ChiefEngineer: 'Geordi La Forge',
Unknown: 'Data'
};
So we need to define all the positions of the ship, but instead of an array
of the positions of the ship, we were given an object of the positions and who holds it.
const positions = Object.keys(starTrekNexGen)
Now positions will be the keys from the object that represented the position on the starShip
console.log(positions) // [ 'Captain', 'ExecutiveOfficer', 'HeadOfSecurityWeaponsOfficer', 'ChiefMedicalOfficer','ChiefEngineer', 'Unknown' ]
I just need the crew members now for a manifest of crew members
const crew = Object.values(starTrekNexGen)
Now I have a list of crew members I can use for different things.
console.log(crew) // [ 'Jean Luc Picard', 'Riker', 'Worf', 'Data' ]
Huh, it seems like there is an 'unknown' position but there is a crew member at the same index.
let's find out which crew member has their position unknown... We can do this from the object itself.
const crewmemberAssignedPos = Object.entries(starTrekNexGen)
So I have an array of arrays
console.log(crewmemberAssignedPos)
[
[ 'Captain', 'Jean Luc Picard' ],
[ 'ExecutiveOfficer', 'Riker' ],
[ 'HeadOfSecurityWeaponsOfficer', 'Worf' ],
[ 'Unknown', 'Data' ]
]
So we want to make sure that Data is assigned to is proper post for work. we don't want him cleaning the latrine by mistake... He would if ordered too so we need to make sure he is posted as Chief Operations Officer.
let arr = [];
const updatedCrewList = crewmemberAssignedPos.reduce((prevVal, arrCrewMemPos) => {
if(arrCrewMemPos[1].includes('Data')) {
arrCrewMemPos[0] = 'ChiefOperationsOfficer'
arr.push(arrCrewMemPos)
} else {
arr.push(arrCrewMemPos)
}
return arr
})
console.log(updatedCrewList)
I plan on modifying and improving the last reduce, I definitely feel there's a better way to do that it was just 11pm at the time π
Top comments (0)