1

I currently have built an API which posts JSON strings of objects. A simple example of the JSON is:

[ {
  "id" : 0,
  "name" : "test SAMPLE Att1 name",
  "attributes" : [ {
    "id" : -1,
    "name" : "AttKey1",
    "value" : "AttValue1"
  }, {
    "id" : -1,
    "name" : "AttKey2",
    "value" : "AttValue2"
  } ]
} ]

My issue lies in my client code here:

function loadSamples() {
  $("#content").children().remove();
  $.getJSON("/api/samples", function (data) {
    $.each(data, function (key, val) {
      $("<tr><td>" + val.id + "</td><td>" + val.name + "</td><td>" + val.attributes + "</td>" +
        "</tr>").appendTo("#content");
    });
    initCallbacks();
  });
}

I am iterating through each sample I send (in this case only one, and appending the field values to the HTML string. How can I iterate through attributes and append each attribute.key and attribute.value to the string?

A picture of the current problem:

enter image description here

2
  • How do you want to format it? val.attributes.reduce(function(pv,v){return ( pv ? pv + ',' : pv ) + v.name + '=' + v.value;}, ''); Commented Jan 25, 2016 at 21:23
  • Why aren't you using JSON.stringify?? Commented Jan 25, 2016 at 21:38

3 Answers 3

3

You can try to use this code instead of val.attributes

$.map(val.attributes, function(item){
   return item.key + ':' +item.value;
}).join(',')
Sign up to request clarification or add additional context in comments.

Comments

3

Use another loop, iterate through all attributes, build an array of attributes in format "property: value" and then append joined array to HTML:

$.each(data, function (key, val) {
  var attributes = [];
  for (var prop in val.attributes) {
    var value = val.attributes[prop];
    attributes.push(prop + ": " + value);
  }
  $("<tr><td>" + val.id + "</td><td>" + val.name +
    "</td><td>" + attributes.join(",") + "</td>" + "</tr>").appendTo("#content");
});

Comments

3

If you feel nerdy you can just serialize the object back into a JSON string like this:

... + JSON.stringify(val.attributes) + ...

It is recursive, has a standard syntax (JSON) and doesn't require any support function or additional code at all.

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.