Get first value from JSON file using forEach

时间:2019-04-17 02:04:26

标签: javascript jquery json ecmascript-6 foreach

I am trying to get the first value from a set of JSON objects. I want to print the first value

This is what I have:

$.getJSON(pt, function(data) {data.forEach(d => {
        console.log(data);
    });

Data Results are: enter image description here When you open any of the array:

     0: Object { page_type: "1" }
​     1: Object { page_type: "2" }
     2: Object { page_type: "3" }
​     3: Object { page_type: "4" }
​     4: Object { page_type: "5" }
​     5: Object { page_type: "6" }
​     6: Object { page_type: "7" }
​     7: Object { page_type: "8" }
​     8: Object { page_type: "9" }
​     9: Object { page_type: "10"}

When I do

$.getJSON(pt, function(data) {data.forEach(d => {
        console.log(d);
    });

I get:

Object { page_type: "1" }
Object { page_type: "2" }
Object { page_type: "3" }
Object { page_type: "4" }
Object { page_type: "5" }
Object { page_type: "6" }
Object { page_type: "7" }
Object { page_type: "8" }
Object { page_type: "9" }
Object { page_type: "10" }

Finally I tired to do

$.getJSON(pt, function(data) {data.forEach(d => {
        console.log(d.page_type);
    });

I get:

1
2
3
4
5
6
7
8
9
10

I want to get 1 only so I tried:

$.getJSON(pt, function(data) {data.forEach(d => {
        console.log(d.page_type[0]);
    });

I am not getting the first value like I want but am getting random values.

Please help!

0 个答案:

没有答案