DEV Community

Heru Hartanto
Heru Hartanto

Posted on

How to get all object values without loop

Es8 has introduced a new cool feature called Object.values() that can be used to get the values of an object.

with Object.values instead of iterating through every element of object we can use it to return all values an object in array.

    const cars = {
        'Toyota': 'Camry',
        'Ford': 'Fiesta',
        'Honda': 'Civic'
    };
    const carsValue = Object.values(cars);

    //['Camry', 'Fiesta', 'Civic']
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

You "can't" get object values iterating over the object because -allegedly- an Object is not an iterable in Javascript.

cars.map( /* whatever */ )
// Uncaught TypeError: cars.map is not a function
Enter fullscreen mode Exit fullscreen mode

Of course as everything is an Object in JS (just like in Python or other languages) you can currently do some tricks like that:

const cars = {
    'Toyota': 'Camry',
    'Ford': 'Fiesta',
    'Honda': 'Civic'
};
const keys = Object.keys(cars);
for(let i=0; i < keys.length; i++) 
    console.log(cars[keys[i]]);

// Camry
// Fiesta
// Civic
Enter fullscreen mode Exit fullscreen mode

I assume you were talking about that.

By the way you can also convert an Object into a key-value Array using Object.entries instead Object.values so you get both the key and the value:

const carsArray = Object.entries(cars);

// [Array(['Toyota', 'Camry'], ['Ford', 'Fiesta'], ['Honda', 'Civic']);
Enter fullscreen mode Exit fullscreen mode

so you can do:

carsArray.find(i => i[0] === 'Toyota')
// ['Toyota', 'Camry']
Enter fullscreen mode Exit fullscreen mode

or

carsArray.find(i => i[1] === 'Camry')
// ['Toyota', 'Camry']
Enter fullscreen mode Exit fullscreen mode

or

carsArray.find(i => i[0] === 'Toyota')[1]
// 'Camry'
Enter fullscreen mode Exit fullscreen mode

You can also play around with objects in even funnier ways like this DOPE thingy.

Hope you find that interesting, have a great day! πŸ‘ŒπŸ˜

Collapse
 
elukuro profile image
Heru Hartanto

Yes that what I were talking about, you could explain it better than me, I hope this will clear things up

have a great day

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

NP, If there's any JS-related topic in which I can help just tell me :)