4 回答
TA贡献1804条经验 获得超8个赞
你可以试试这个-
const obj = {
"India" : {
"Karnataka" : ["Bangalore", "Mysore"],
"Maharashtra" : ["Mumbai", "Pune"]
},
"USA" : {
"Texas" : ["Dallas", "Houston"],
"IL" : ["Chicago", "Aurora", "Pune"]
}
};
const search = (obj, keyword) => {
return Object.values(obj).reduce((acc, curr) => {
Object.entries(curr).forEach(([key, value]) => {
if (value.indexOf(keyword) > -1) {
acc.push(key);
}
});
return acc;
}, []);
}
console.log(search(obj, 'Pune'));
这将搜索keyword数组中是否存在。如果然后将钥匙推入reduce蓄电池。
TA贡献1936条经验 获得超6个赞
假设您的数据将始终采用 country:state:city 的形式,您可以执行以下操作。获取键的数组,如下所示:
keys = Object.keys(obj);
然后遍历每个键:
function classify(input){
res = [];
Object.keys(obj).forEach((key)=>{
states = obj[key];
Object.keys(states).forEach((stateKey)=>{
if(states[stateKey].includes(input)){
res.push([stateKey,key]);
}
})
})
return(res);}
这也将返回一个包含国家/地区的数组:
input: Pune
output: [['Maharashtra','India'],['IL','USA']]
TA贡献1891条经验 获得超3个赞
const input = "Pune"
const result = []
for (v1 in obj) {
for (v2 in obj[v1]) {
for (let i = 0; i < obj[v1][v2].length; i++) {
if (obj[v1][v2][i] === input) {
result.push([v2][0])
}
}
}
}
TA贡献1796条经验 获得超4个赞
function isObject (variable) {
return variable !== undefined && variable !== null && variable.constructor === Object
}
function find(obj,value,keyPath = []){
let values = Object.values(obj)
let keys = Object.keys(obj)
for(let i in values){
if(isObject (values[i])) {
find(values[i],value,keyPath )
}else if(Array.isArray(values[i])){
let foundValue = values[i].find(e=>value==e)
if(foundValue ){
keyPath.push(keys[i])
}
}
}
return keyPath
}
obj = { "India": { "Karnataka": ["Bangalore", "Mysore"], "Maharashtra": ["Mumbai", "Pune"] }, "USA": { "Texas": ["Dallas", "Houston"], "IL": ["Chicago", "Aurora", "Pune"] } }
console.log(find(obj,"Dallas"))
这应该这样做。它应该能够做任何深度。
添加回答
举报