如果我輸入任何變數,我希望能夠使用 getValue 并迭代 myObject 鍵來獲取鍵值“f”。
result = "f";
或者
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);
}
}
}
uj5u.com熱心網友回復:
你的意思是找到哪個陣列包含值的鍵?
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))
選擇
const getByValue = (obj,val) => Object.entries(obj)
.reduce((acc,[key,arr]) => (arr.includes(val) && acc.push(key),acc),[])[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))
使用查找表(靈感來自vitaly-t 的回答)
這是假設所有陣列中的唯一值
const makeLookup = obj => Object.entries(obj).reduce((acc,[key,arr]) => (arr.forEach(val => acc[val] = key),acc),{});
const getByValue = (tbl,val) => tbl[val] ?? "N/A";
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
const lookUp = makeLookup(myObject);
console.log(JSON.stringify(lookUp))
console.log(getByValue(lookUp,1))
console.log(getByValue(lookUp,99))
console.log(getByValue(lookUp,6))
uj5u.com熱心網友回復:
@mplungjans 回答使用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))
uj5u.com熱心網友回復:
如果訪問同一物件的速度很重要,那么最好Map先從該物件創建一個,然后您可以立即檢索每個值:
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
const qm = new Map(Object.entries(myObject)
.flatMap(([key, val]) => val.map(a => ([a, key]))));
const getByValue = (val) => qm.get(val) ?? 'N/A';
console.log(getByValue(1)); //=> f
console.log(getByValue(99)); //=> N/A
console.log(getByValue(6)); //=> g
如果某些值在陣列中不是唯一的,則后面的每個值都將覆寫前一個值。
顯示代碼片段
const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
const qm = new Map(Object.entries(myObject)
.flatMap(([key, val]) => val.map(a => ([a, key]))));
const getByValue = (val) => qm.get(val) ?? 'N/A';
console.log(getByValue(1));
console.log(getByValue(99));
console.log(getByValue(6));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534276.html
上一篇:在二維陣列中連續向后迭代
