gpt4 book ai didi

javascript - 将数组保存为键中的值并循环遍历它们以获取键

转载 作者:行者123 更新时间:2023-12-05 04:20:44 25 4
gpt4 key购买 nike

如果我输入任何变量,我希望能够使用 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);
}
}
}

最佳答案

您的意思是找到包含该值的数组的键?

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's 答案)

这是假设所有数组的值都是唯一的

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))

关于javascript - 将数组保存为键中的值并循环遍历它们以获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74411852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com