I want to be able to use getValue and iterate myObject keys to get the key value "f" if i input any variable.
result = "f";
Or
result = " g";
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
let getValueOne = 1;
function getKeyByValue() {
for (let i = 0; i < myObject[value].length; i ) {
result = myObject.key[i];
if (i === getValueOne) {
console.log(result);
}
}
}
CodePudding user response:
You mean find the key which array contains the value?
const getByValue = (obj,val) => Object
.entries(obj)
.filter(([key,arr]) => arr.includes(val))
.map(([key,arr]) => key)[0] || "N/A";
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
console.log(getByValue(myObject,1))
console.log(getByValue(myObject,99))
console.log(getByValue(myObject,6))
CodePudding user response:
@mplungjans answer using Array.find
const getByValue = (obj, val) =>
(Object.entries(obj).find(([key, arr]) =>
arr.find(v => val === v)) || [`N/A`]).shift();
const myObject = {
f: [1, 2, 3, 4, 5],
g: [6, 7, 8, 9, 10]
};
console.log(getByValue(myObject,1))
console.log(getByValue(myObject,99))
console.log(getByValue(myObject,6))