function getObjKey(obj, value) {
return Object.keys(obj).find(key => obj[key] === value);
}
const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};
console.log(getObjKey(obj, ['Santiago','Germany']));
I want to get the key of ['Santiago','Germany'] this array value as city1
console.log(getObjKey(obj, 'Chicago'));
When I try the above code, I am getting the key of 'Chicago' as city2.
Same way I want to get the key of ['Santiago','Germany'] as well. How can I do that?
Any suggestions?
CodePudding user response:
You can use JSON.stringify.
Example:
function getObjKey(obj, value) {
return Object.keys(obj).find(key => Array.isArray(obj[key]) ? JSON.stringify(obj[key]) === JSON.stringify(value) : obj[key] === value) ;
}
const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};
console.log(getObjKey(obj, 'Chicago'));
console.log(getObjKey(obj, ['Santiago','Germany']));
Output:
city2
city1
CodePudding user response:
You can use Object.entries()
,
check if the value is an array or not and Check if the value exists like so:
function getObjKey(obj, value) {
return Object.entries(obj).find(([k, v]) => {
if(Array.isArray(v)) {
return v.every(item => value.includes(item));
}
return v === value;
})?.[0];
}
const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};
console.log(getObjKey(obj, ['Santiago','Germany']));
console.log(getObjKey(obj, 'Chicago'));
CodePudding user response:
You need to check whether obj[key]
is an Array
or not if Array then use every
to check it matches with all values and if it's not just check obj[key]===value
const getObjKey = (obj, value) => {
return Object.keys(obj).find(key => {
const currVal = obj[key];
return Array.isArray(currVal) && Array.isArray(value) && currVal.length === value.length ? value.every(val => currVal.includes(val)) : currVal === value
});
}
const obj = {
city1: ['Santiago', 'Germany'],
city2: 'Chicago',
city3: 'Berlin'
};
console.log(getObjKey(obj, ['Santiago', 'Germany']));
console.log(getObjKey(obj, 'Chicago'));
console.log(getObjKey(obj, ['Santiago', 'Germany', 'Erlangen']));
console.log(getObjKey(obj, ['Berlin']));
CodePudding user response:
You can't compare arrays with ===
, a temporary solution can be parse the values as strings and then check if they are equal:
function getObjKey(obj, value) {
return Object.keys(obj).find(key => JSON.stringify(obj[key]) === JSON.stringify(value));
}
But as I said, this should be a temporary solution since it would be slow for larger objects.