将数组元素作为值推送到对象中

3
我希望将一个数组转换成以下这样的对象:
array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9" ]
   
pages = {"page1" :["blue","txt2", "red"] , "page2" : ["txt4", "txt5", "txt6"], "page3" : ["txt7" ,"txt8", "txt9"]   
pages 对象中的每个键都应该有一个数组值,该数组包含3个元素的子数组(最后一个键可以少于3个元素),例如,如果有一个110元素的数组,则会有37个 pages(page1,page2,...,page37),而page37只有1个元素。
因此,我想将数组中的每3个元素作为一个键的值放入 pages 对象中。
但是我不知道如何做。谢谢您的帮助。

创建具有递增键的对象是否有原因?为什么不创建一个数组的数组呢? - adiga
@adiga 可能是因为代码可以直接在 HTML 页面上显示键作为页码,尽管显示“转到第1页”确实很奇怪。 - ophact
3个回答

5
你可以通过迭代 array 数组并使用 splice 方法,在每次迭代中从 array 中提取 3 个项目来完成此操作,像这样:

let array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9", "text10" ]
let pages= {}, i= 1;
while(array.length > 0){
    pages[`page${i++}`] = array.splice(0,3)
}

console.log(pages)

以这种方式,您会失去数组中的原始值。如果要保留数组中的项目不受影响,可以像这样复制原始数据:let copiedArray = [...array],然后在copiedArray上调用splice方法,并在while中检查copiedArraylength

0

获取每隔三个索引,从该点到该点加三个元素的所有元素(如果该索引接近结尾,则不会出错;它将只添加剩余的元素):

const initial = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

let paginated = {};
let counter = 0

while (counter < initial.length) {
 paginated['page' + parseInt(counter / 3 + 1)] = initial.slice(counter, counter + 3);
 counter += 3;
}
 
console.log(paginated);


只是一个小备注。当您定义计数器并将此计数器用作结束循环的条件时,使用while循环有点奇怪。这感觉像是一个简单的for循环的理想工作 :) - Wimanicesir
@Wimanicesir 的确,我知道这一点。我只是习惯于在 Python 中使用 while 循环来递增计数器直到达到某个特定点;) - ophact

0

如果您需要更多配置选项,可以考虑使用 chunk 实用函数来对输入数组进行初始分割,然后按需将其映射到结果对象(这里使用 Object.fromEntries 并在分块数组上映射以基于索引分配“page”键)。

function chunk(arr, chunkSize) {
  const result = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize));
  }

  return result;
}

const array = ['blue', 'txt2', 'red', 'txt4', 'txt5', 'txt6', 'txt7', 'txt8', 'txt9'];

const result = Object.fromEntries(
    chunk(array, 3).map((chunk, index) => [`page${index + 1}`, chunk])
);

console.log(result);

参见:将数组拆分成块 进行讨论。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接