user3378165 user3378165 - 6 months ago 19
Javascript Question

How to add line breaks in a mapped array?

I have to folowing KO Object:

var Property= function (data) {
this.name= ko.observable(data[0].name);
this.address = ko.pureComputed(function () {
return data.map(function (prop) {
return prop.address;
});
}, this);
}


The JSON 'data' is as follow:


[{"name":"Name1","address":"Address1"}{"name":"Name1","address":"Address2"}]


When I show on the page the 'address' property,

<span data-bind="text: address"></span>


It looks like this:


Address1 ,Address2


My question is how can I seperate between the addresses with a line break instead of a comma?


Address1

Address2


I tried that:

var Property= function (data) {
this.name= ko.observable(data[0].name);
this.address = ko.pureComputed(function () {
return data.map(function (prop) {
return prop.address + '\n';
});
}, this);
}


But the output was:


Address1 \n,Address2 \n


Any idea how to do it?

Answer

\n is not how HTML like breaks works. You need to use proper layout for that, at the minimum, use <br />.

You can concatenate your entries like this:

return data.map(function (prop) {
      return prop.address;
}).join('<br/>');

Also, you need to bind the value as HTML for markup to be retained, use:

<span data-bind="html: address"></span>