0

That is jSON request

http://www.omdbapi.com/?s=harry

Follow the link to see the structure of response. How can I get a number of objects in order to create for loop?

2 Answers2

0

First you need to JSON.parse the data (string) in this case:

var data = JSON.parse(string);

Getting the number of items is:

data.length;

You can do the same with a file (assuming node.js):

require('fs').readFile(JSON.parse(file), 'utf8', function (err, data
{
    if (err) throw err;
    // your data is now parsed
});

Then you iterate using a for-loop the array you're interested in:

for (var prop in data)
{
    // do something with item
    var item = data[prop];
}

Iteration nowadays doesn't require the a-priori knowledge of the array length:

for (var i = 0; i < data.length; ++i)

That JSON seems to have a Search array of objects (see for your self: http://json.parser.online.fr/)

Ælex
  • 14,432
  • 20
  • 88
  • 129
  • Do you really mean to use `for each`? – Felix Kling Feb 06 '16 at 03:30
  • @FelixKling yes, why not? – Ælex Feb 06 '16 at 03:32
  • Because that's only supported by Firefox afaik: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in . – Felix Kling Feb 06 '16 at 03:33
  • @FelixKling npm/node.js also supports it afaik, albeit with different syntax. – Ælex Feb 06 '16 at 03:34
  • 1
    *"npm/node.js also supports it afaik"* Probably not that syntax since Chrome (V8) doesn't support it. *"albeit with different syntax"* Maybe you mean [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of), which is part of ES6 (and fine to use). You shouldn't suggest something that is deprecated. – Felix Kling Feb 06 '16 at 03:35
  • 1
    @FelixKling replaced with for - in :-) – Ælex Feb 06 '16 at 03:38
  • 1
    :) In that case you should probably change the variable name since `item` is not the property name and `data[item]` would be the value. – Felix Kling Feb 06 '16 at 03:39
0
response.Search.map(function(obj){
   //loop here
});

instead of using for loop

melvnberd
  • 3,093
  • 6
  • 32
  • 69
  • 2
    What exactly does this have to do with jQuery? Also, `.map` is not for looping. Use `.forEach` instead. – Felix Kling Feb 06 '16 at 03:32
  • 1
    ops I just leaned that `.map` function isnt a jquery function hence its a raw javascript function.. sorry for that @FelixKling :3 . also researched about difference between `.map` vs `forEach` but I cant still get why .map isnt for looping xD – melvnberd Feb 06 '16 at 03:49