【问题标题】:将数组的元素作为值推送到对象
【发布时间】:2022-01-23 16:45:43
【问题描述】:

我想将数组更改为这样的对象:

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 个数组元素的数组值(最后一个键可以少),例如,如果一个数组有 110 个元素,我们将有 37 个 pages(第 1 页,第 2 页, ... , page37) 和 page37 将有 1 个元素。

所以我想将数组中的每 3 个元素作为 pages 对象中键的值

但我不知道该怎么做。。谢谢你的帮助

【问题讨论】:

  • 是否有理由使用增量键创建对象?为什么不创建一个数组数组?
  • @adiga 可能是这样代码可以直接在 HTML 页面上将键显示为页码,虽然确实显示“转到第 1 页”很奇怪

标签: javascript arrays


【解决方案1】:

您可以通过迭代 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)

通过这种方式,您会丢失array 中的原始值,如果您想保留array 中的项目,您可以复制您的原始数据,如let copiedArray = [...array],然后调用 splice 方法copiedArray 并在while 中检查lengthcopiedArray

【讨论】:

    【解决方案2】:

    对于更可配置的解决方案,您可以使用 chunk 实用函数来对输入数组进行初始划分,然后根据需要将其映射到您的结果对象(此处使用 Object.fromEntries 并映射到生成的分块数组根据索引分配“页面”键)。

    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);

    请参阅:Split array into chunks 进行讨论。

    【讨论】:

      【解决方案3】:

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

      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 确实,我知道这一点。我只是习惯于在 Python 中使用 while 循环将计数器递增到某个点;)
      猜你喜欢
      • 2020-11-17
      • 2019-12-22
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多