How to take position of the Object (Indice)

Asked

Viewed 2,499 times

0

How to get the position of the object that was found in $.inArray() ?

    var obj = [
    {
        cidade : [
            {
                nome : "Maringá" ,
                uf : "PR" ,
            } ,

            {
                nome : "Curitiba" ,
                uf : "PR" ,
            } ,

            {
                nome : "Londrina" ,
                uf : "PR" ,
            }
        ]
    } ,
    {
        estado : [
            {
                nome : "Paraná" ,
                sigla : "PR"  ,
                regiao : "sul"
            } ,
            {
                nome : "São Paulo" ,
                sigla : "SP"  ,
                regiao : "sul"
            } ,
            {
                nome : "Rio Grande do Sul" ,
                sigla : "PR"  ,
                regiao : "sul"
            }
        ]
    }
];
    exemplo.init();
  • 1

    Can you explain it better? want to know the position / index of the object that has a certain name within the "state" array for example?

  • Can Douglas explain the question better? It’s unclear what he intends to do. Explaining better will get a better answer too.

2 answers

3

As described in documentation of $.inArray(), when it finds the element it returns the position it is in, if the element does not exist it returns -1.

  • So, if it finds, the return will be the position of the array, this ?

  • 1

    Yes, but remembering that it will only search inside the array, it doesn’t work if you want to search for object inside object.

2


do so:

function procurar(objeto_, procurado_) {    
    var encontrou = false;
    var retorno = [];   
    function recursiva(objeto)
    {               
        if(typeof objeto === 'object')
        {
            for(var i in objeto)
            {
                retorno.push(i);                
                recursiva(objeto[i]);               
                if(encontrou)
                {
                    break;
                }
                retorno.pop();
            }
        }
        else
        {           
            if(objeto === procurado_)
            {
                encontrou = true;
            }
        }       
    }   
    recursiva(objeto_); 
    return retorno;
}

then create a function to test:

function testa_procurar() {
    var procurado = 'Londrina';
    var localizacao = procurar(obj, procurado);
    console.log('localizacao: ' + localizacao); 
}

exit: 0,city,2,name

Then just implement other features!

  • thanks for the reply, served me very well.

  • And if you wanted to add one more City object, or one more state object, as you would hook state?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.