3

I have the code below that works, but I need to expand it, so I am attempting to make it more streamlined.

success: function setData(data) {
            $("#price" + lastchar).html(data.price);
            $("#matricule" + lastchar).html(data.matricule);
            $("#tag" + lastchar).html(data.tag);
            $("#ins_yr1" + lastchar).html(data.ins_yr1);
            $("#Totalacq" + lastchar).html(data.Totalacq);
        }

Like this:

success: function (data){
  var desc=[];
  desc = ["price","matricule","tag","ins_yr1","Totalacq"];
  for (var i=0;i<desc.length;i++){
    $( "#" + desc[i] + lastchar).html(data.desc[i]);
  }
}

But this does not work because it does not accept a variable desc[i] within the .html(), at least not in the format I am trying to do it.

Any ideas? Thanks!

2 Answers 2

3

Your problem is not in html, but in the way you're trying to access data properties. But you can get/set them using [], just like array indices:

data[desc[i]]

In other words, data.price is equivalent to data["price"].

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

1 Comment

I realized I could make it even shorter by referencing the keys of the data file as below: success: function (data){ var keys=[]; keys = Object.keys(data); for (var i=0;i<keys.length;i++){ $( "#" + keys[i] + lastchar).html(data[keys[i]]); } }
1

Just lo leave that as reference for future use, I realized I could make it even shorter, by referencing directly the keys of the array object.

success: function (data){

    var keys = Object.keys(data);
    for (var i=0;i<keys.length;i++){
        $( "#" + keys[i] + lastchar).html(data[keys[i]]);
    }
}

1 Comment

You dont need var keys = [] and then keys = Object.keys(data), just go straight to var keys = Object.keys(data).

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.