DEV Community

Cover image for Javascript Object #14
Asir-Sam
Asir-Sam

Posted on

Javascript Object #14

In the Post we are going to some latest ECMA method introduced in Javasciript.

Object.values()

To access the value of an Object we usually use for...in loop to iterate over it and access the elements inside the Object.But there is problem with for...in as we have already seen this in past post about for...in loop,that iterates over all the inherited properties of an Object.That is not fair and we have sort that it with Object.hasOwnProprty() method.That's a Good way, but what if we can do it in more easy way.

ES2017 has introduced the Object.values to access the values of an own enumerable properties of an Object.

let's see this with an example,

`const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25
};

for (const key in person) {
    if (person.hasOwnProperty(key)) {
        const value = person[key];
        console.log(value);

    }
}
`
Enter fullscreen mode Exit fullscreen mode

OUTPUT

`John
Doe
25
`
Enter fullscreen mode Exit fullscreen mode

Let's now see this with the Object.values(),

The Syntax is,

`Object.values(obj)`
Enter fullscreen mode Exit fullscreen mode
`const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25
};

const profile = Object.values(person);

console.log(profile);
`
Enter fullscreen mode Exit fullscreen mode

OUTPUT

`[ 'John', 'Doe', 25 ]
`
Enter fullscreen mode Exit fullscreen mode

The Object.values() accepts an object and returns its own enumerable property’s values as an array.

Object.entries()

As like Object.values(),in ES2017 introduced the Object.entries.

Object.entries are same like Object.values,but it returns the enumerable string-keyed property into [key, value] pair of Object.

`Object.entries()`
Enter fullscreen mode Exit fullscreen mode
`const ssn = Symbol('ssn');
const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    [ssn]: '123-345-789'
};

const kv = Object.entries(person);

console.log(kv);
`
Enter fullscreen mode Exit fullscreen mode

OUTPUT

`[
    ['firstName', 'John'],
    ['lastName', 'Doe'],
    ['age', 25]
]
`
Enter fullscreen mode Exit fullscreen mode
The firstName, lastName, and age are own enumerable string-keyed property of the person object, therefore, they are included in the result.
The ssn is not a string-key property of the person object, so it is not included in the result.
Enter fullscreen mode Exit fullscreen mode

That's all for now,hope you learnt something.Please put down comments suggesting me to do better,that will motivates me a lot to do more in Javascript.

Thanks for you Time in between breaks,
Sam

Top comments (0)