4 回答
TA贡献1828条经验 获得超4个赞
在此:
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)
TA贡献1802条经验 获得超5个赞
用途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));
TA贡献1895条经验 获得超3个赞
您可以编写一个小函数来为您完成此操作。该函数在第一次找到代码时进行匹配。
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
,因为它默认提取属性名称。
TA贡献1807条经验 获得超9个赞
您需要迭代 的键/值对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))
添加回答
举报