-3

I have the following JSON:

{"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]}

I need to access weekends to get this:

6
8
15

Here is my try:

var json = $.parseJSON(data);
for (var i = 0, len = data.weekends.length; i < len; i++) {
    console.log(data.weekends[i]);
}

But results are empty in chrome console log...if I understand correctly...i read length of json converted to an array and for in loop I read the value in the index array.

But I always get the error:

Uncaught TypeError: Cannot read property 'length' of undefined

Why is weekends length undefined? I set command length and it does not recognize it is an array and to count length so that for loop can work.

fool-dev
  • 7,671
  • 9
  • 40
  • 54
Igor Petev
  • 597
  • 2
  • 6
  • 24
  • 8
    you're parsing into a variable called `json` but are using the unparsed `data` in the loop... – baao Jan 07 '18 at 11:24
  • Use `json.weekends.length` in `for` loop and inside it, use `0` index to print data. – Tushar Jan 07 '18 at 11:26
  • Yes you are right..thanks...i uses data and must json..now it works great..thanks for helping me out..i spend 1hour trying to get why this does not work...now it works – Igor Petev Jan 07 '18 at 11:26

2 Answers2

0
var data = {"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]};
for (var i = 0, len = data.weekends.length; i < len; i++){
    console.log(data.weekends[i]);
}
Danny Mcwaves
  • 159
  • 1
  • 6
Devang Patel
  • 51
  • 1
  • 2
0

The problem is that you are accessing weekend using data, which is just raw JSON String. You need to access the json variable, which is the parsed JSON.

Below is the working code:

const data = {"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]};

// To avoid calculation of length on every iteration
const weekendLength = data.weekends.length;

for(let i = 0; i < weekendLength; i++){
    console.log(data.weekends[i][0]);
}

Here, I am setting the JSON data directly to a variable. In your case, you are most probably getting the data from a network request. In that case, as you did in your code, you need to parse it first. (By calling $.parseJSON())

code
  • 2,115
  • 1
  • 22
  • 46