-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?

4
  • 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. Commented Jul 12, 2020 at 6:52
  • was this an Angularjs question? Commented Jul 12, 2020 at 7: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. Commented Jul 12, 2020 at 7:43
  • I guess you mean angular, not angularJS, since you mentionned typescript. Somethibg like this? stackblitz.com/edit/… Commented Jul 12, 2020 at 7:50

1 Answer 1

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

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

3 Comments

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.
I used in-built 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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.