Information



Tags



Share

How to use Object.keys() and Object.values() in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement


Best VPN Service
Best VPN


Definition

In this tutorial, I will show you how to use the Object.keys() method and the Object.values() method to create an instantly-responsive-string generator.

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.(1)

Object.values() returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually.(2)

Code

Using the querySelector method, select each year's checkbox.

Create a year book object consisting of names of the attendants.

Check whether a year selected or not.

If selected, collate data in the 'selected' object.

Using ?:(Ternary) operator, for each selected year, add names of the attendants to the result string.

Using Object.keys() and Object.values(), obtain data from the 'selected' object as arrays whose elements corresponding to the enumerable properties.

Show the result string.

var year_97 = document.querySelector('input[name="1997"]');
var year_98 = document.querySelector('input[name="1998"]');
var year_99 = document.querySelector('input[name="1999"]');

const year_book = {
    year_97: " / John, Alicia, Steve",
    year_98: " / Robert, Tim, Scarlett",
    year_99: " / Judy, Kimmy, Lilly"
};

function generate(){
	generate_result_string(year_97.checked, year_98.checked, year_99.checked);
}

function generate_result_string(is_97_selected, is_98_selected, is_99_selected){

let result_string = "";

const selected = {
     year_97: is_97_selected,
     year_98: is_98_selected,
     year_99: is_99_selected
};

for(var i=0;i<Object.keys(selected).length;i++){
	result_string += (Object.values(selected)[i]) ? year_book[Object.keys(selected)[i]] : "";
}

document.getElementById("show").innerHTML = result_string;

}

Result:

Select a year to add to the result string.

1997:

1998:

1999:

References

(1) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

(2) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values