-4

I am quite new to web development and hence have a doubt in implementing this.

var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"} ]];
var strObj = JSON.stringify(obj);
var dmodPayload = modPayload.replace(/[{]/g, '\n');

I want the array elements to be printed on separate lines. The output that I get here is [[\n"name":"John","age":30,"city":"New York,\n"name":"Ken","age":35,"city":"New Orleans"}]]

But I want it as [[ "name":"John","age":30,"city":"New York"},
"name":"Ken","age":35,"city":"New Orleans"}]]

If I use < br >, it gets replaced as < br > and no line break is see. How do I insert a break between two array elements of a JSON object after it has been converted into a string?

David
  • 33,444
  • 11
  • 80
  • 118
vp_5614
  • 41
  • 8
  • 4
    This has nothing to do with Typescript (and nothing to do with JSON either, that's an array of objects, not JSON.) You have to show how you're printing the array. – Guy Incognito Jul 12 '20 at 06:52
  • was this an Angularjs question? – rexfordkelly Jul 12 '20 at 07:37
  • I want this to be seen on my webpage as an entry in a tabular column and yes it's an angularJS question. I'm very new to angular, sorry if the question wasn't framed right. – vp_5614 Jul 12 '20 at 07:43
  • I guess you mean angular, not angularJS, since you mentionned typescript. Somethibg like this? https://stackblitz.com/edit/angular-ivy-atvfus?file=src%2Fapp%2Fapp.component.ts – David Jul 12 '20 at 07:50

1 Answers1

0

Make use of NgFor

<div *ngFor="let js of obj">
  <div [innerHTML]="js | json"></div>
  <!-- <br/> --> <!-- add br tag if required -->
</div>
var obj = [{ name: "John", age: 30, city: "New York"}, 
           { name: "Ken", age: 35, city: "New Orleans"} ]; // correct array

enter image description here

stackblitz

Chenna
  • 2,383
  • 3
  • 20
  • 36
  • Hi! Thank you for this answer, it does solve my question. But I wanted to know how to do it after converting obj into a string. I have this format to follow where I need to print it as a string. – vp_5614 Jul 12 '20 at 07:27
  • I used in-built [JsonPipe](https://angular.io/api/common/JsonPipe) in angular to convert array to string. Happy to help if you could explain the use case if possible. So you want to have `[` also displayed? – Chenna Jul 12 '20 at 07:34
  • I want to show the obj as an entry in a tabular column. I don't want [ ] and { } to be displayed. Only the elements on separate lines. – vp_5614 Jul 12 '20 at 07:37