You can easily separate keys and values from a JSON object in JavaScript using the Object.keys()
and Object.values()
methods.
1. Using Object.keys()
and Object.values()
Object.keys()
returns an array of all the keys in the JSON object.Object.values()
returns an array of all the values in the JSON object.
Here's a simple example:
const myJSON = {
"name": "John Doe",
"age": 30,
"city": "New York"
};
const keys = Object.keys(myJSON);
const values = Object.values(myJSON);
console.log(keys); // Output: ["name", "age", "city"]
console.log(values); // Output: ["John Doe", 30, "New York"]
2. Using for...in
Loop
You can also use a for...in
loop to iterate through the JSON object and access its keys and values individually.
const myJSON = {
"name": "John Doe",
"age": 30,
"city": "New York"
};
for (const key in myJSON) {
console.log(`Key: ${key}, Value: ${myJSON[key]}`);
}
This will output:
Key: name, Value: John Doe
Key: age, Value: 30
Key: city, Value: New York
3. Using Object.entries()
The Object.entries()
method returns an array of key-value pairs as arrays.
const myJSON = {
"name": "John Doe",
"age": 30,
"city": "New York"
};
const entries = Object.entries(myJSON);
console.log(entries); // Output: [["name", "John Doe"], ["age", 30], ["city", "New York"]]
You can then access the keys and values from each entry using array indexing.
Conclusion
By using these methods, you can easily extract keys and values from a JSON object in JavaScript and work with them separately.