How to get the key of a key/value JavaScript object
If you want to get all keys, ECMAScript 5 introduced Object.keys
. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in
btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
Of course if you want both, key and value, then for...in
is the only reasonable solution.
How to get a key in a JavaScript object by its value?
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
ES6, no prototype mutations or external libraries.
Example,
function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value);}
const map = {"first" : "1", "second" : "2"};console.log(getKeyByValue(map,"2"));
How to get a key/value pair for an object
Here you go. To get key/value pair
from an object, do it like below using pure JavaScript way Object.entries():
var a = {"e":1,"d":3,"f":4}
for (const [key, value] of Object.entries(a)) { console.log(`${key} ${value}`);}
Getting key with the highest value from object
For example:
var obj = {a: 1, b: 2, undefined: 1};
Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
In ES6:
var obj = {a: 1, b: 2, undefined: 1};
Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
get key corresponding to value in js object
You can simply fetch all the keys using Object.keys()
and then use .find()
function to get the key out from that array, and then nicely wrap it in a function to make it modular.
var inspectionMapping = { 'a_pillar_lh': "A Pillar LH", 'b_pillar_lh': "B Pillar LH"};
Object.prototype.getKey = function(value) { var object = this; return Object.keys(object).find(key => object[key] === value);};
alert(inspectionMapping.getKey("A Pillar LH"));
how to get the object key if the object and array value matches in javascript
You can simply iterate through the array, and then attempt to fetch the [key, value]
tuples returned by Object.entries(obj)
whose value
matches the array value. Once found, you return the key
in the tuple, i.e.:
arr.map(v => Object.entries(obj).find(x => x[1] === v)[0]);
Note: If you array may contain values that are not present in the object, the code above will throw an error because .find()
will return undefined. If that's the case, you need to catch cases where an invalid value is used (defensive design):
arr.map(v => {
const foundTuple = Object.entries(obj).find(x => x[1] === v);
return foundTuple ? foundTuple[0] : null;
});
See proof-of-concept below:
const obj = {
"active": 12,
"inactive": 14,
"neutral": 16
}
const arr1 = [12];
const arr2 = [12, 14];
const arr3 = [12, 16];
const invalid_arr = [12, 999];
function getKeys(obj, arr) {
return arr.map(v => {
const foundTuple = Object.entries(obj).find(x => x[1] === v);
return foundTuple ? foundTuple[0] : null;
});
}
console.log(getKeys(obj, arr1));
console.log(getKeys(obj, arr2));
console.log(getKeys(obj, arr3));
console.log(getKeys(obj, invalid_arr));
how to display both key and value in object using javascript?
You can use Object.entries.
let list = {eb: 'blue', et: 'green'}
const keyValue = (input) => Object.entries(input).forEach(([key,value]) => { console.log(key,value)})
keyValue(list)list = {er: 'yellow', ex: 'black'}keyValue(list)
Swap key with value in object
function swap(json){
var ret = {};
for(var key in json){
ret[json[key]] = key;
}
return ret;
}
Example here FIDDLE don't forget to turn on your console to see the results.
ES6 versions:
static objectFlip(obj) {
const ret = {};
Object.keys(obj).forEach(key => {
ret[obj[key]] = key;
});
return ret;
}
Or using Array.reduce() & Object.keys()
static objectFlip(obj) {
return Object.keys(obj).reduce((ret, key) => {
ret[obj[key]] = key;
return ret;
}, {});
}
Or using Array.reduce() & Object.entries()
static objectFlip(obj) {
return Object.entries(obj).reduce((ret, entry) => {
const [ key, value ] = entry;
ret[ value ] = key;
return ret;
}, {});
}
Related Topics
How to Load Local Script Files as Fallback in Cases Where Cdn Are Blocked/Unavailable
How to Toggle an Element's Class in Pure JavaScript
Differencebetween State and Props in React
Get All Attributes of an Element Using Jquery
Caching a Promise Object in Angularjs Service
Angularjs 1.2 $Injector:Modulerr
Need to Escape a Special Character in a Jquery Selector String
Make Browser Window Blink in Task Bar
Do You Ever Need to Specify 'Javascript:' in an Onclick
Basic JavaScript Promise Implementation Attempt
Safari 3Rd Party Cookie Iframe Trick No Longer Working
How Many Bytes in a JavaScript String
Check If an Element Is Present in an Array
How to Return Values from Async Functions Using Async-Await from Function
How to Set Default Homepage in Ff and Chrome via JavaScript
How to Call Loading Function with React Useeffect Only Once
How to Get the Selected Text in a Textarea
How to Fix Jslint Error 'Don't Make Functions Within a Loop.'