Index of an array element in Mustache.js

前端 未结 6 963
后悔当初
后悔当初 2020-12-06 01:31

This is what I\'d like to do in Mustache.js but not seeing how with the documentation.

var view = {items:[\'Mercury\',\'Venus\',\'Earth\',\'Mars\']};
var tem         


        
6条回答
  •  囚心锁ツ
    2020-12-06 01:55

    (Tested in node 4.4.7, moustache 2.2.1.)

    If you want a nice clean functional way to do it, that doesn't involve global variables or mutating the objects themselves, use this function;

    var withIds = function(list, propertyName, firstIndex) {
        firstIndex |= 0;
        return list.map( (item, idx) => {
            var augmented = Object.create(item);
            augmented[propertyName] = idx + firstIndex;
            return augmented;
        })
    };
    

    Use it when you're assembling your view;

    var view = {
        peopleWithIds: withIds(people, 'id', 1) // add 'id' property to all people, starting at index 1
    };
    

    The neat thing about this approach is that it creates a new set of 'viewmodel' objects, using the old set as prototypes. You can read the person.id just as you would read person.firstName. However, this function doesn't change your people objects at all, so other code (which might have relied on the ID property not being there) will not be affected.

提交回复
热议问题