0

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"

Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
asked Jul 6, 2020 at 19:43

4 Answers 4

1

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>

answered Jul 6, 2020 at 19:52
Sign up to request clarification or add additional context in comments.

Comments

1

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>

answered Jul 6, 2020 at 19:47

Comments

1

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?

answered Jul 6, 2020 at 19:48

Comments

1

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.

answered Jul 6, 2020 at 19:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.