0

I've returned JSON data from controller (via ajax), and wanna access to this data. This is a list of objects (array): key - value, so I wanna use .each() to access all data. Array like that:

[{"filePath":"Desktop.zip","fileStatus":"Uploaded"},{"filePath":"Desktop\\dates.xml","fileStatus":"Uploaded"}]

and code is:

$.ajax({
                    url: '@Url.Action("GetFilesNames", "Home")',
                    type: 'POST',                    
                    success: function (data) {                      

                        $.each(data, function (value) {
                            console.log(value['filePath'], value['fileStatus']);

                            });
                    }
                });

First picture, data isn't loaded

But data.each value is undefined.

So I've tried to console.log all data, json.stringify it, parse it (but somehow with error), and parse stringyfied version, but in makes no sense. Even If I use this stringified version (paths) or parsed stringified version (listOfFiles) with .each - same result: undefined.

enter image description here

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
pad0n
  • 187
  • 3
  • 17
  • At the top of your `success` function, `data` is an array. That is what you want. **Don't** try converting it to JSON (which isn't useful) or from JSON (because it isn't JSON). – Quentin Sep 03 '18 at 14:01
  • @Quentin ok, I get it. But if I have an array, so what should I do to get data value by it's key? Why my code `$.each(data, function (value) { console.log(value['filePath'], value['fileStatus']); });` isn't working? – pad0n Sep 03 '18 at 14:05
  • Possible duplicate of [How to loop through array in jQuery?](https://stackoverflow.com/questions/3943494/how-to-loop-through-array-in-jquery) – Kirk Larkin Sep 03 '18 at 14:05

1 Answers1

2

See the documentation for jQuery.each:

callback
Type: Function( Integer indexInArray, Object value )

Now see your code:

$.each(data, function (value) {

You are trying to read the properties from the first argument, which is an Integer (the index in the array() and not the value. You need to be reading properties from the second argument.

 $.each(data, function (index, value) {
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335