Home >Web Front-end >JS Tutorial >How to use Object.keys() and Object.values() methods in js?
In the previous article [How to use the Object.entries() method] we learned that using the entries() method can use the [key, value] pair of the object as an array element, in the form of an array Iterate over the output. So if you just want to traverse a single key value or value value in the [key, value] pair in the form of an array, how can you implement it? This article will introduce to you how to use the Object.keys() method and the Object.values() method to output a single key value or value value in an object [key, value] pair.
Object.keys() method
The Object.keys() method can convert an object as parameters, and then traverse the key values in the [key, value] pair of this object in the form of an array.
Basic syntax:
Object.keys(obj)
Object.values() method
Object The .values() method can take an object as a parameter, and then traverse the value values in the [key, value] pair of this object in the form of an array.
Basic syntax:
Object.values(obj)
Usage of Object.entries() and Object.values() methods
1. List all key attributes or value attributes of the object, for example:
var obj ={ name: '小明', age: '20岁', sex: '男' }; console.log(Object.keys(obj)); console.log(Object.values(obj));
Output:
It can be seen that using Object. The keys() method traverses the key and outputs: name, age, sex; uses the Object.values() method to traverse the value and outputs: Xiao Ming, 20 years old, male.
2. List the key attributes or value attributes specified in the object, for example:
var obj ={ name: '小明', age: '20岁', sex: '男' }; console.log(Object.keys(obj)[0]); console.log(Object.values(obj)[0]);
Output:
It can be seen that, Specify the key value "name" in the first [key, value] pair of the returned object, and the value value "Xiao Ming" in the first [key, value] pair.
3. Return ordered values based on random key values
var obj ={ 70: 'x', 20: 'y', 35: 'z' }; console.log(Object.keys(obj)); console.log(Object.values(obj));
Output:
Summary: The above is this The entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to use Object.keys() and Object.values() methods in js?. For more information, please follow other related articles on the PHP Chinese website!