Created
June 6, 2021 23:04
-
-
Save vuongtran/1cf6d4406dac814bd5cf7e89f5a94d96 to your computer and use it in GitHub Desktop.
How to deal with key value pairs in JavaScript object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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