【发布时间】:2021-05-22 21:42:23
【问题描述】:
我有一个具有以下属性的对象:
const rows_obj = {
prova1:[{price:3,description:"test11"},{price:7,description:"test12"}],
prova2:[{price:11,description:"test21"},{price:2,description:"test22"}],
prova3:[{price:1,description:"test31"},{price:23,description:"test32"}],
}
并且我需要在一页或多页中打印行,因此每页的限制例如为 3 行。所以在这种情况下,我需要一个对象 obj 数组,例如:
obj[0] = {
total:21,
prova1:[{price:3,description:"test11"},{price:7,description:"test12"},],
prova2:[{price:11,description:"test21"}],
}
obj[1] = {
total:26,
prova2:[{price:2,description:"test22"}],
prova3:[{price:1,description:"test31"},{price:23,description:"test32"},],
}
(因为在这种情况下,限制是每页/对象 3 行)
但限制也可能是 20 行,因此最终对象将是:
obj[0] = {
total:47,
prova1:[{price:3,description:"test11"},{price:7,description:"test12"},],
prova2:[{price:11,description:"test21"},{price:2,description:"test22"},],
prova3:[{price:1,description:"test31"},{price:23,description:"test32"},],
}
因为在原始对象中有6行,那么,由于在限制之下,函数必须检索一个包含一个元素的数组,并且这个元素等于原始的那个。
我试过了,但到目前为止我已经编写了这个代码:
const size = 3
const rows_obj = {
prova1:[{price:22,description:"test11"},{price:23,description:"test12"},],
prova2:[{price:22,description:"test21"},{price:23,description:"test22"},],
prova3:[{price:22,description:"test31"},{price:23,description:"test32"},],
}
var rows_length = 0;
for(var char in rows_obj){
// Confirm that the key value is an array before adding the value.
if(Array.isArray(rows_obj[char])){
rows_length += rows_obj[char].length;
}
}
if (!rows_length) {
return [[]]
}
const arrays = []
let i = 0
const keys = Object.keys(rows_obj)
let obj = null
while (i<rows_length) {
obj = {}
for(let j=0;j<keys.length;j++) {
obj[keys[j]] = rows_obj[keys[j]].slice(i, i + size)
i = i + 2 + size
console.log(i)
}
arrays.push(obj)
}
它不工作,我做的一团糟......有什么帮助吗?提前谢谢你。
【问题讨论】:
-
录像机。这绝对不是stackoverflow.com/q/11318680 的重复。输入和输出结构都不同。
标签: javascript algorithm