Alan Alan - 1 month ago 7
HTML Question

Reformat JSON objects inside an array to show them in HTML

I'm trying to find a way to reformat an array of JSON objects that looks like:

[{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}]


I want to only print the values in plain html text. For example:

3 - Coca-Cola
3 - Rib Eye


How can i achieve this? My back end is Node.js so yeah maybe I can do that before building the html i will use.

Answer

Just iterate over your array, saving the formatted strings to another array. You can pass the created array to your page and display it, or do whatever you want.

var json = "[{\"amount\":3,\"name\":\"Coca-Cola\"},{\"amount\":3,\"name\":\"Rib Eye\"}]",
    arr = JSON.parse(json),
    formatted = [];
arr.forEach(function(item) {
  formatted.push(item.amount + " - " + item.name);
});

In the above code, the array formatted contains the strings as you need them.

Comments