Skip to content

Instantly share code, notes, and snippets.

@vuongtran
Created June 6, 2021 23:04
Show Gist options
  • Save vuongtran/1cf6d4406dac814bd5cf7e89f5a94d96 to your computer and use it in GitHub Desktop.
Save vuongtran/1cf6d4406dac814bd5cf7e89f5a94d96 to your computer and use it in GitHub Desktop.
How to deal with key value pairs in JavaScript object
const test = {a: 1, b: 2, c: 3};
// #1 ES6
for (const [key, value] of Object.entries(test)) {
console.log(key, value);
}
// #2
for (var k in test){
if (test.hasOwnProperty(k)) {
alert("Key is " + k + ", value is " + test[k]);
}
}
// #3
Object.keys(test).forEach(function (key) {
// do something with obj[key]
});
// #4
for( var key in test ) {
var value = test[key];
}
// #5
Object.values(test).forEach(value => ...); // Select value
Object.keys(test).forEach(key => ...); // Select key
Object.entries(test).forEach(([key, value])=> ...); // Select [key, value]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment