Javascript Object Values & Object Keys

The Javascript Object has some methods available on it that make it easier to iterate over it’s properties or it’s values. Object.values which was introduced by ES2017 outputs values of a javascript object into an array and Object.keys outputs the keys as an array.

const students = {
    jules: 27,
    leo: 30,
    bella: 19,
    ella: 36
};

In the above students (likely graduate students 😏) we can output just the ages of the students by using Object.values(). We can conversely output just the names of the students by using Object.keys(). This can be useful if want to order the students alphabetically or order them by age, for example:

const orderedByName = {};

Object.keys(students).sort((a, b) => {
    return a.localeCompare(b);
}).forEach((key) => {
    orderedByName[key] = students[key];
});

console.log(orderedByName);
> {bella: 19, ella: 36, jules: 27, leo: 30}

Let’s order them by age:

const orderedByAge = {};

Object.keys(students).sort((a,b) => {
    return students[a] - students[b];
}).forEach((key) => {
    orderedByAge[key] = students[key];
})

console.log(orderedByAge);
> {bella: 19, jules: 27, leo: 30, ella: 36}

If for some reason you get an error message that says Object.values isn’t available, you can also use Object.map to obtain the same effect.

const values = Object.keys(students).map((key) => {
    return students[key];
});

Lastly, there is the Object.entries which returns an array of arrays of each key and value:

const students = {
    jules: 27,
    leo: 30,
    bella: 19,
    ella: 36
};

Object.entries(students);

// Will display this
[
  [
    "jules",
    27
  ],
  [
    "leo",
    30
  ],
  [
    "bella",
    19
  ],
  [
    "ella",
    36
  ]
]

Instagram Post