1

I have json like this:

obj = [{"name":"Jim Smith","role":"Author"},{"name":"Julie Smith","role":"Author"}]

I would like to print the name of the authors like this:

<div class="authors">Authored by Jim Smith & Julie Smith</div>

I am iterating through the object like this:

$.each( obj, function(k,v) {    
  $('.authors').append('<span>' + v.name + '</span>');
});

This outputs

<div class="authors">Authored by Jim SmithJulie Smith</div>

Ideally, a solution will also take into account 1, 2, and 2+ authors such that if there are more than 2 authors, only the last author will have the &amp; prefix the value.

For example: if there are three authors: Jim Smith, Julie Smith, & John Smith

Notice the usage of the oxford comma.

Should I wrap it in an if statement? How best to iterate through an $.each loop while keeping track of the length of the return and which iteration is active?

2
  • 1
    What about this : w3schools.com/jsref/jsref_join.asp it can help you ?it is a join function for an array Commented Nov 28, 2018 at 21:00
  • that's very promising and succinct, I'll see if it fits the solutions. thanks for sharing. Commented Nov 28, 2018 at 21:25

1 Answer 1

1

One way to achieve this would be to use map() to build an array of the names from your initial object array. Then you can apply the logic from this answer to join the values together in the manner you require for displaying in the UI. Try this:

var arr = [{
  "name": "Jim Smith",
  "role": "Author"
}, {
  "name": "Julie Smith",
  "role": "Author"
}, {
  "name": "Foo Smith",
  "role": "Author"
}];

var names = arr.map(function(o) { return o.name; }).join(', ').replace(/,(?!.*,)/gmi, ' and');
$('.authors span').text(names);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="authors">Authored by <span></span></div>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.