我需要在sampledata
内添加page:1。请注意,sampledata
是固定的,我需要在每个page:1
之后添加另一个值array
。
var sampledata = [
{ id:1, title:'Title 1'},
{ id:2, title:'Title 2'},
{ id:3, title:'Title 3'},
{ id:4, title:'Title 4'},
{ id:5, title:'Title 5'},
{ id:6, title:'Title 6'}
];
我创建了一个循环以添加页面及其值。
for( var a = 0; a < sampledata.length; a++ ){
sampledata[a].page = 1;
}
现在,sampledata
的打印方式如下:
var sampledata = [
{ id:1, title:'Title 1', page:1},
{ id:2, title:'Title 2', page:1},
{ id:3, title:'Title 3', page:1},
{ id:4, title:'Title 4', page:1},
{ id:5, title:'Title 5', page:1},
{ id:6, title:'Title 6', page:1}
];
如何实现输出sampledata
的页面,其值如下所示?
var sampledata = [
{ id:1, title:'Title 1', page:1},
{ id:2, title:'Title 2', page:1},
{ id:3, title:'Title 3', page:2},
{ id:4, title:'Title 4', page:2},
{ id:5, title:'Title 5', page:3},
{ id:6, title:'Title 6', page:3}
];
答案 0 :(得分:2)
您可以获取索引并获取除以2(或任何其他值)的整数值,并以1而不是0的值开始页面值。
var data = [{ id: 1, title: 'Title 1'}, { id: 2, title: 'Title 2'}, { id: 3, title: 'Title 3'}, { id: 4, title: 'Title 4'}, { id: 5, title: 'Title 5'}, { id: 6, title: 'Title 6'}],
itemsPerPage = 2,
result = data.map((o, i) => Object.assign({}, o, { page: Math.floor(i / itemsPerPage) + 1 }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
如果只想基于索引和page
添加pageSize
属性,则可以像这样使用Math.floor()
:
var sampledata = [{ id: 1, title: 'Title 1'}, { id: 2, title: 'Title 2'}, { id: 3, title: 'Title 3'}, { id: 4, title: 'Title 4'}, { id: 5, title: 'Title 5'}, { id: 6, title: 'Title 6'}];
var pageSize = 2; // change to whatever you need
sampledata.forEach((o, i) => o.page = 1 + Math.floor(i/pageSize))
console.log(sampledata)