javascript get key and value from object code example
Example 1: how to find the key of an value in an object
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const map = {"first" : "1", "second" : "2"};
console.log(getKeyByValue(map,"2"));
Example 2: javascript iterate object key values
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
Example 3: foreach key value javascript
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
Example 4: for key value in object javascript
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
Example 5: js find key by value in object
Object.keys(object).find(key => object[key] === value)
Example 6: get all keys of object in javascript
myObject = {
"key": "value",
"key2":"value2"
}
Object.keys(myObject);