Display comma separated values as list items:

2019-09-14 22:33发布

问题:

This is a continuation from this question: How to display comma delimited JSON value as a list?

I have this array:

var ARTISTS: Artist[] = [
  {
     "name": "Barot Bellingham",
     "shortname": "Barot_Bellingham",
     "reknown": "Royal Academy of Painting and Sculpture",
     "bio": "Some bio here...",
     "friends": [
       "james",
       "harry",
       "bob"
    ]
  },
  // etc...
]

And I need to display "friends" as an ordered list. I'm doing so like this:

<li *ngFor="let friend of artist.friends">{{friend}}</li>

This works perfectly, but, I now need to restructure my data so that there is no nested array:

var ARTISTS: Artist[] = [
  {
     "name": "Barot Bellingham",
     "shortname": "Barot_Bellingham",
     "reknown": "Royal Academy of Painting and Sculpture",
     "bio": "Some bio here...",
     "friends": "James, Harry, Bob"
  }

How can I continue to display each friend as separate list items, such as:

<ol>
  <li>James</li>
  <li>Harry</li>
  <li>Bob</li>
</ol>

Thank you!

回答1:

Simply use the toString() method to display the list of a string separated by commas.

var friends = ['a', 'b', 'c'];
console.log(friends.toString());

So in your case you could just change this:

<li *ngFor="let friend of artist.friends">{{friend}}</li>

to this for example:

<div>{{artist.friends.toString()}}</div>

If you want to change the separator, or add a space after the commas, you can use the join() method of arrays too:

var friends = ['a', 'b', 'c'];
console.log(friends.join(', '));

Instead if now you have in your model the list as a string separated by comma, use the ng-repeat recreating an array from the string in this way:

<li *ngFor="let friend of artist.friends.split(', ')">{{friend}}</li>