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

3
  • 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). Commented Sep 3, 2018 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? Commented Sep 3, 2018 at 14:05
  • Possible duplicate of How to loop through array in jQuery? Commented Sep 3, 2018 at 14:05

1 Answer 1

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) {
Sign up to request clarification or add additional context in comments.

1 Comment

HOLY COW... now I get it.. It's working! Thanks ! Feel so dumb now

Your Answer

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.