[Answered ]-Convert JSON from Django to JavaScript Array and Loop to Populate 'users' Parameter in Mention.js

2👍

From the source of mention.js it looks like users is expected to be array of JS objects, so no function inside array will work. Also matching is performed on username fields and name is just for displaying results. So I think you should set not only name-s and avatar-s, but also username-s.

Idealy, if your Django model for user will contain username, it will look like this:

$("#some-field").mention({
    // other fields
    users: profile_array.map(function (profile) {
        return {
            username: profile.fields.username,
            name: profile.fields.name,
            avatar: profile.fields.avatar
        };
    })
 });

But of course, you could convert names into usernames by yourself on the JS side, with something like:

// converts names into usernames
// ex: 'Bob Jones' -> 'bob_jones'
function nameToUsername(name) {
   return name.toLowerCase().replace(/\s+/g, '_');
}

And then use it in code that creates users array:

$("#some-field").mention({
    // other fields
    users: profile_array.map(function (profile) {
        return {
            username: nameToUsername(profile.fields.name),
            name: profile.fields.name,
            avatar: profile.fields.avatar
        };
    })
 });

Leave a comment