Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
search for value in json and return the main key

i have a json with structure like this

{
  "india": {
    "north_states": ["TN", "AP", "MP", "AB"],
    "south_states": ["PB", "UP", "RJ", "HR"]
  },
  "us": {
    "north_states": ["AC", "AD", "AE", "AF"],
    "south_states": ["BA", "BB", "BC", "BD"]
  },
}

Now if I search for "UP", I have to get south_states and india as reply. how do i do that in JavaScript?

For example:

I need to get the country name based upon the input given in search. for example if i get the input value as 'UP' i need to search the json where UP is and get its key (south_states) and i also need to get the country name as india. the result should take the input of state acronym name and give both the keys as country name and the state_location(south or north)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would iterate in this fashion:

the code might need some tweaking, but it works.

this uses recursion, to iterate the JSON to find the objects/array's that match. If the structure of the JSON is fixed, it could be even easier.

const countries = { "india":{"north_states":["TN","AP","MP","AB"],"south_states":["PB","UP","RJ","HR"]}, "us":{"north_states":["AC","AD","AE","AF"],"south_states":["BA","BB","BC","BD"]}, };


function findItems(data, value, pkey){
  let results = [];
  for(let key of Object.keys(data)){
      let newData = data[key];
      if(typeof(newData) == 'string'){
          if(newData == value){
            results.push(pkey);
          }
      } else {
        results = findItems(newData, value, key).concat(results);
      }
  }
  if(results.length > 0 && pkey && results.indexOf(pkey) == -1){
    results.push(pkey);
  }
  return results;
}

let search = findItems(countries, 'UP');

console.info(search);

For a fixed structure, and only on result should be found:

    const countries = { "india":{"north_states":["TN","AP","MP","AB"],"south_states":["PB","UP","RJ","HR"]}, "us":{"north_states":["AC","AD","AE","AF"],"south_states":["BA","BB","BC","BD"]}, };


    function findItems(data, searchTerm){
      let results = [];
      for(let country of Object.keys(data)){
          let stateGroups = data[country];
          for(let stateGroupName of Object.keys(stateGroups)){
            let stateGroup = stateGroups[stateGroupName];
            if(stateGroup.indexOf(searchTerm)!=-1){
              return [country, stateGroupName];
            }
          }
      }
     
    }

    let search = findItems(countries, 'UP');

    console.info(search);

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Parse the JSON into a JS object that you can loop over.

  2. Loop over the main object properties, and then loop over each of those object's properties, and if any of those arrays includes the value you want to match, return the key of the main object, and the key of the inner object.

const json = '{"india":{"north_states":["TN","AP","MP","AB"],"south_states":["PB","UP","RJ","HR"]},"us":{"north_states":["AC","AD","AE","AF"],"south_states":["BA","BB","BC","BD"]}}';

const data = JSON.parse(json);

function check(data, val) {
  for (let key in data) {
    for (let innerkey in data[key]) {
      if (data[key][innerkey].includes(val)) {
        return [key, innerkey];
      }
    }
  }
  return 'No match';
}

console.log(check(data, 'UP'));
console.log(check(data, 'BO'));
console.log(check(data, 'AF'));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda