mocart
mocart

Reputation: 615

jquery each for json

I get JSON from my endpoint:

[{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}]

after it, i use:

data = jQuery.parseJSON(data);

how i can show data from json with jquery each? i try to do this but it not works correctly:

$.each(data, function (key, data2) {
    $.each(data2, function (index, value) {
    console.log(value['phone']);
});

for ex, it must show (with jquery) only phones, like:

71111111111
72222222222
73333333333

but show me "undefined"

Upvotes: 0

Views: 54

Answers (4)

Cid
Cid

Reputation: 15247

Remove the inner loop.

The outer one already provide you the expected object, such as {"phone":71111111111,"debt":1}

The inner one will enumerate the values of those objects 71111111111 and 1 in the above example.

(71111111111)['phone'] is undefined, because there are no property phone in the number 71111111111

const json = '[{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}]';

const data = jQuery.parseJSON(json);

$.each(data, function (key, data2) {
      console.log(data2['phone']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Sagar Patil
Sagar Patil

Reputation: 521

There is no need to do a $.each again. data2 is the object in which phone is contained, so all you have to do is this:

$.each(data, function(key, data2){
    console.log(data2['phone']);
}

This yeilds the correct output.

I also want to note that you do not have to use $.each() in order to loop through an array. Instead, you can use foreach.

Upvotes: 1

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

Why don't you use the Vanilla forEach method? You can do your job like-

data.forEach(({phone, debt}) => {
  console.log(phone);
});

It's easy and pure, isn't it?

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89224

You only need to use jQuery.each once to loop over the array of objects. It is crucial to note that the first argument given to the callback is the index and the second one is the actual element.

var data = [{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}];
$.each(data, function (idx, obj) {
    console.log(obj.phone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions