javascriptsharepointjslink

How to iterate an array of objects and print out one of its properties


I have the following code in a display template in sharepoint, I have an array of objects and I need to have the following result.

Name1
Name2
Name3

So I can replace the default rendering of sharepoint multiple people user field with a tooltip.

However, I dont know how to iterate and then concatenate:

Screenshot: enter image description here

Code:

// List View - Substring Long String Sample 
// Muawiyah Shannak , @MuShannak 

(function () { 

    // Create object that have the context information about the field that we want to change it's output render  
    var projectTeamContext = {}; 
    projectTeamContext.Templates = {}; 
    projectTeamContext.Templates.Fields = { 
        // Apply the new rendering for Body field on list view 
        "Project_x0020_Team": { "View": ProjectTeamTemplate } 
    }; 

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(projectTeamContext); 

})(); 

// This function provides the rendering logic 
function ProjectTeamTemplate(ctx) { 

    var projectTeamValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name]; 

    //newBodyvalue should have the list of all display names and it will be rendered as a tooltip automaticlaly

    return "<span title='" + projectTeamValue + "'>" + newBodyValue + "</span>"; 

} 

Solution

  • You can "map" property values from the projectTeamValue array objects into a new array, then "join" those values together (using ", " as the separator in this example) all in one go:

    var newBodyValue = projectTeamValue.map(function(person) {
        return person.value;
    }).join(", ");
    

    If your projectTeamValue array looked like:

    [{ value: "Name1" }, { value: "Name2" }, { value: "Name3" }]
    

    Then newBodyValue would be:

    "Name1, Name2, Name3"
    

    Side note: Array.prototype.map() was not available in IE 8 and below but should work in every other browser.