简体   繁体   中英

How to search for a value in Object which contains sub objects with as array values

I have json object and i want to search for a key in it and return that Object key as a result if the key matches. consider the following example

obj = {
    "India": {
        "Karnataka": ["Bangalore", "Mysore"],
        "Maharashtra": ["Mumbai", "Pune"]
    },
    "USA": {
        "Texas": ["Dallas", "Houston"],
        "IL": ["Chicago", "Aurora", "Pune"]

    }
}
input: Pune
output: ['Maharashtra','IL']
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])
      }
    }
  }
}

You can try this-

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

This will search if the keyword exists inside the array. If then push the key into the reduce accumulator.

Assuming your data will always be of the form country:state:city, you can do something like this. Get an array of the keys as follows:

keys = Object.keys(obj);

Then loop through each key:

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

This will return an array with the country as well:

input: Pune
output: [['Maharashtra','India'],['IL','USA']]

Another way to do it:

function findCityInState(city) {
  var statesWithCity=[];
  for(country in obj) {
    for(state in obj[country]) {
      if(obj[country][state].includes(city)) {
        statesWithCity.push(state);
      }
    }
  }
  return statesWithCity;
}
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"))

This should do it. It should be able to do any depth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM