Skip to content Skip to sidebar Skip to footer

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': { 'Ka

Solution 1:

You can try this-

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


constsearch = (obj, keyword) => {
  returnObject.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.

Solution 2:

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

Solution 3:

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:

functionclassify(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']]

Solution 4:

Another way to do it:

functionfindCityInState(city) {
  var statesWithCity=[];
  for(country in obj) {
    for(state in obj[country]) {
      if(obj[country][state].includes(city)) {
        statesWithCity.push(state);
      }
    }
  }
  return statesWithCity;
}

Solution 5:

functionisObject (variable) { 

return variable !== undefined && variable !== null && variable.constructor === Object

}

functionfind(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 )
          
      }elseif(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.

Post a Comment for "How To Search For A Value In Object Which Contains Sub Objects With As Array Values"