如果我輸入任何變數,我希望能夠使用 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))
使用查找表(受vitally-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 createMap = (obj) => new Map(Object.entries(obj)
.map(([key, val]) => val
.map(a => ([a, key])))
.flat());
const qm = createMap(myObject); // your instant-access map;
const getByValue = (m, val) => m.get(val) ?? 'N/A';
console.log(getByValue(qm, 1)); // f
console.log(getByValue(qm, 99)); // N/A
console.log(getByValue(qm, 6)); // g
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/532088.html
