我试图从一个具有随机网格大小的API中创建一个动态网格。我可能不会正确地问这个问题(因此我找不到我需要的东西),但我需要的是能够对数组进行同样的标记。这是一个场景,数组长度为10。
0: { id: 1, title: "First Element" }
1: { id: 3, title: "Second Element" }
2: { id: 5, title: "Third Element" }
3: { id: 7, title: "Forth Element" }
4: { id: 9, title: "Fifth Element" }
5: { id: 11, title: "Sixth Element" }
6: { id: 13, title: "Seventh Element" }
7: { id: 15, title: "Eigth Element" }
8: { id: 17, title: "Nineth Element" }
9: { id: 19, title: "Tenth Element" }例如,我希望附加对象以添加名为class的新属性;
我需要0,1,2,3是col-2,4是col-4,其余的项目是相同的重复。5,6,7,8是col-2,9是col-4。
但是相同的-不能有一个1/2的单位,然后是一个全宽度的单位,并需要最后一个项目是全宽度。
预期结果:
0: { id: 1, title: "First Element", class: 'col-2' }
1: { id: 3, title: "Second Element", class: 'col-2'}
2: { id: 5, title: "Third Element", class: 'col-2' }
3: { id: 7, title: "Forth Element", class: 'col-2' }
4: { id: 9, title: "Fifth Element", class: 'col-4' }
5: { id: 11, title: "Sixth Element", class: 'col-2' }
6: { id: 13, title: "Seventh Element", class: 'col-2' }
7: { id: 15, title: "Eigth Element", class: 'col-2' }
8: { id: 17, title: "Nineth Element", class: 'col-2' }
9: { id: 19, title: "Tenth Element", class: 'col-4' }
10: { id: 21, title: "Last Element", class: 'col-4' }功能:
this.renderContent = function() {
if (this.retrievedNewsArticles == null || this.retrievedNewsArticles.length == 0) {
$(contentContainerElement).html('<p class="inline-message">There is currently no data to display.</p>');
} else {
// The loop is here
for (var i = 0; i < this.retrievedNewsArticles.length; i++) {
this.addUnit(this.retrievedNewsArticles[i]);
}
}
};插件建议欢迎。
发布于 2017-04-18 17:07:28
这应该适用于你:
var arr = [
{ id: 1, title: "First Element" },
{ id: 3, title: "Second Element" },
{ id: 5, title: "Third Element" },
{ id: 7, title: "Forth Element" },
{ id: 9, title: "Fifth Element" },
{ id: 11, title: "Sixth Element" },
{ id: 13, title: "Seventh Element" },
{ id: 15, title: "Eigth Element" },
{ id: 17, title: "Nineth Element" },
{ id: 19, title: "Tenth Element" },
{ id: 21, title: "Last Element" }
];
var lastElIndex = arr.length - 1;
var test = arr.map((item, index) => {
// edit per OP request
if ( (index + 1) % 5 === 0) {
item['className'] = 'col-4';
}
//if ( (index + 1) % 5 === 0) {
// return { id: item.id, title: item.title, className: "col-4" };
} else if (index === lastElIndex) {
return { id: item.id, title: item.title, className: "col-4" };
} else {
return { id: item.id, title: item.title, className: "col-2" };
}
});我们在这里要做的是遍历数组并将className属性映射到每个项,具体取决于(index + 1) mod 5是否为真。
编辑:添加了最后一个元素要求。我第一次读的时候就错过了。我道歉。
https://stackoverflow.com/questions/43478072
复制相似问题