1

I am trying to call an object property value and append it to the div "file-path-info". The function that appends JSON data to "file-size-info" works. What am I doing wrong with my second statement?

My JSON data:

{"maxFileSize" : "10 MB", "fileList" :  [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}]}

HTML and JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="file-size-info"></div>
<div id="file-path-info"></div>

<script>

    $.getJSON('http://localhost/MISREST/helpdocs', function (data) {
  $.each( JSON.parse(data), function ( key, val ) {
    if (key == "maxFileSize") {$("#file-size-info").append(val);};

      if (key == "fileList") {$("#file-path-info").append(["fileList"]["href"]);};

  });
    });

</script>
1
  • 2
    ["fileList"]["href"] ? Commented May 16, 2017 at 13:49

2 Answers 2

2

It should be

if (key == "fileList") {
   $("#file-path-info").append(val[0]["href"]);
};

assuming you only have one value in fileList, if not then you need to loop over the values.

as for the fileList key , val gives you

[
  {
    "fileName": "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat",
    "href": "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"
  }
]

and then you need to extract href from the first object.

Sign up to request clarification or add additional context in comments.

2 Comments

Note: This is assuming OP wants to show only the first element in the fileList array. And not the entire list of files.
In the second case he should be mapping over the array values, I will update the answer in case the OP comes back with a updated question
1
if (key == "maxFileSize") {$("#file-size-info").append(val);};

In that block of code maxFileSize is the key and val is the value of that property (the string 10 MB).

Following that pattern, when fileList is the key, val would be the value of that property: [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}] (an array containing a single item that is an object).

You'll need to index the array to get the item at index 0 (the only item) and grab the value of that object's href property in order to use it:

if (key == "fileList") {$("#file-path-info").append(val[0].href);};

Comments

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.