-
明月笑刀无情
在此:const search_q = 4512;let k = null;const items = { storeItems: { milk_code: [1212, 9898, 1214], vegetables_code: [2222, 75674, 8943, 3452], eggs_code: [4543, 4512, 1754, 9090] }}Object.keys(items.storeItems).forEach(item => { if(items.storeItems[item].includes(search_q)) k = item;})console.log(k)
-
慕后森
用途Object.entries及find方法const items = { storeItems: { milk_code: [1212, 9898, 1214], vegetables_code: [2222, 75674, 8943, 3452], eggs_code: [4543, 4512, 1754, 9090], },};const getKey = (obj, val) => Object.entries(obj) .find(([key, arr]) => arr.includes(val)) ?.shift(); console.log(getKey(items.storeItems, 4512));
-
蛊毒传说
您可以编写一个小函数来为您完成此操作。该函数在第一次找到代码时进行匹配。const items = { store_items: { milk_code: [1212, 9898, 1214], vegetables_code: [2222, 75674, 8943, 3452], eggs_code: [4543, 4512, 1754, 9090] }}function find_code( code, object ) { for( const property in object ) if( object[property].includes(code) ) return property; return undefined;}console.log( find_code( 4512, items.store_items ) );console.log( find_code( 1200, items.store_items ) );console.log( find_code( 8943, items.store_items ) );请注意,您正在迭代 an Object,而不是Array. for..of您可以使用或迭代对象for..in。我使用了for..in,因为它默认提取属性名称。
-
函数式编程
您需要迭代 的键/值对storeItems,搜索值以返回键const findKey = (obj, search) => { for (let [ key, val ] of Object.entries(obj)) { if (val.includes(search)) return key } return null}const items = { storeItems: { milk_code: [1212, 9898, 1214], vegetables_code: [2222, 75674, 8943, 3452], eggs_code: [4543, 4512, 1754, 9090] }}console.info(findKey(items.storeItems, 4512))这将返回找到的第一个具有匹配值的键(按定义顺序)。如果该值可以出现在多个值中并且您想要返回所有匹配项,则可以使用简单的过滤器const findKeys = (obj, search) => { return Object.keys(obj).filter(key => obj[key].includes(search))}const items = { storeItems: { milk_code: [1212, 9898, 1214, 4512], // added 4512 here vegetables_code: [2222, 75674, 8943, 3452], eggs_code: [4543, 4512, 1754, 9090] }}console.info(findKeys(items.storeItems, 4512))