DEV Community

loading...

A Few Useful Objects Methods, built-ins Part 1

Jacob Evans
FullStack Software Engineer @ Cloudflare | Air Force Veteran | Hardware Enthusiast | Outdoorsman | OSS Enthusiast & Contributor
・2 min read

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'
};
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

I just need the crew members now for a manifest of crew members

const crew = Object.values(starTrekNexGen)
Enter fullscreen mode Exit fullscreen mode

Now I have a list of crew members I can use for different things.

console.log(crew) // [ 'Jean Luc Picard', 'Riker', 'Worf', 'Data' ]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

So I have an array of arrays

console.log(crewmemberAssignedPos) 
 [
     [ 'Captain', 'Jean Luc Picard' ],
     [ 'ExecutiveOfficer', 'Riker' ],
     [ 'HeadOfSecurityWeaponsOfficer', 'Worf' ],
     [ 'Unknown', 'Data' ]
  ]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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 😆

Discussion (0)