Search Here

Explained with Examples Javascript Object.values() method for Beginners

Explained with Examples Javascript Object.values() method for Beginners

Javascript Object.values() method returns arrays of object’s properties and methods whose enumerable property is set to true.It takes an object as an argument.

Syntax

Object.values(obj)

Examples

person = {
    "fname" : "John",
    "lname" : "Junior",
    "age" : 12,
    "get_full_name" : function(){
        return this.fname+" "+this.lname
    }
}

console.log(Object.values(person))

//Console Output
(4) ["John", "Junior", 12, ƒ]

Object person has three properties and one function get_full_name() which returns and if we pass this object to .values() the method then a list of items are returned which are values of the property. If a property has a function then it will also be returned to the list. In the above example ƒ is a function.

student_marks = {
    "english" : 56,
    "maths" : 45,
    "science" : 60,
    "social" : 61,
    "moral_science" : 81,
}

function addMarks(obj){
    let tot_marks = 0;
    for(var marks of Object.values(obj)){
        tot_marks+=marks
    }

    return tot_marks;
}

console.log("Total Marks secured : ",addMarks(student_marks));

//Console Output
Total Marks secured :  303

We can use this method to calculate the sum of total marks scored by students.

Set enumerable property to false to exclude properties and methods from Object.values() method.
When object enumerable property is defined as false.

student_marks = {
    "english" : 56,
    "maths" : 45,
    "science" : 60,
    "social" : 61,
}

Object.defineProperty(student_marks, "moral_science",{value:81,enumerable : false})
console.log(student_marks);

console.log("Object Values : ",Object.values(student_marks));

//Console Output
Object Values :  (4) [56, 45, 60, 61]

We have assigned 5 properties and property moral_science is set to enumerable:false.So property moral_science is not iterable in the loop.

Conclusion

So its time to say goodbye we have come to the end of our post on Explained with Examples Javascript Object.values() method for Beginners. If you like our content then please do share it and comment to clarify your doubt.

Related Posts

Summary
Review Date
Reviewed Item
Explained with Examples Javascript Object.values() method for Beginners
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development