Browse a json in Javascript with jQuery

1

I have a json like this

result= {"cambios":[{"idCard":"5ac8798039a4cff62f780f8e","idList":"5ab7c3aec0fa3a36a67b1c87"},{"idCard":"5ab7c3cc83270bcf19c2774f","idList":"5ab7c3aec0fa3a36a67b1c87"}]}

I want to access idCard and idList, I am testing as follows:

function modificarLista(result){
     alert("Estoy en cambiar de lista" + result.cambios);
     alert("Estoy en cambiar de lista" + result);

     $("#res2").text(result.cambios);
     $("#res3").text(result);

       $.each(result.cambios, function(i, item) {
            $("#res2").text("en el each"+ item.idCard);
            alert(item.idCard);
            alert(item.idList);
        });
};

I think my mistake is that I directly go through the array, and I still have to go "changes" but I do not know what I'm missing

    
asked by Silvia 15.04.2018 в 13:27
source

2 answers

2

At the beginning it can be a bit messy, but look at the example:

result= {"cambios":[{"idCard":"5ac8798039a4cff62f780f8e","idList":"5ab7c3aec0fa3a36a67b1c87"},{"idCard":"5ab7c3cc83270bcf19c2774f","idList":"5ab7c3aec0fa3a36a67b1c87"}]};

$.each(result.cambios, function(i, item) {
    $("#res2").text("en el each");
    alert(item.idCard);
    alert(item.idList);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="res2"></div>

As you can see, the first modification I have made is to change the element that you are going to go through. You will not go through 'result' but 'result.changes'. By doing this, the item variable takes that value and you just have to refer to idCard or idList.

    
answered by 15.04.2018 / 13:47
source
1

in the jquery documentation there are examples, this is one of the examples.

<script>
var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };

jQuery.each( obj, function( i, val ) {
  $( "#" + i ).append( document.createTextNode( " - " + val ) );
  console.log(i + " val: " + val)
});

var ejemplo = {
                "cambios":[
                            {
                                "idCard":"5ac8798039a4cff62f780f8e",
                                "idList":"5ab7c3aec0fa3a36a67b1c87"
                            },
                            {   
                                "idCard":"5ab7c3cc83270bcf19c2774f",
                                "idList":"5ab7c3aec0fa3a36a67b1c87"
                            }
                          ]
              }


jQuery.each( ejemplo, function( i, val ) {

    jQuery.each( val, function( x, valor ) {

      console.log( valor.idCard)
    });
});
</script>

As I see you have an object, which contains a property of type array and inside that you have objects, it would be question that you enter the first array to be able to access the property that contains the objects. this an improbisation, serious question that you analyze and see a way to solve. I hope I help you

    
answered by 15.04.2018 в 15:52