猿问

将数组转换为单独的对象数组

我有一个数组,我想将此数组转换为单独的对象,很高兴帮助我,谢谢


array = ["January", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, "February", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

我想


result  = [

   {

     month:'January',

     days:[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

   },

   {

     month:'February',

     days:[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

   }

]


ITMISS
浏览 69回答 1
1回答

开满天机

&nbsp; &nbsp; 首先找出数组中字符串的索引,以便可以拆分数组。const process = (arr) => {&nbsp; const result = [];&nbsp; let last = -1;&nbsp; for (let i = 0; i <= arr.length; i++) {&nbsp; &nbsp; if (typeof arr[i] === "string" || !(i in arr)) {&nbsp; &nbsp; &nbsp; if (last !== -1) {&nbsp; &nbsp; &nbsp; &nbsp; result.push([last, i]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; last = i;&nbsp; &nbsp; }&nbsp; }&nbsp; return result.map(([start, end]) => ({&nbsp; &nbsp; month: arr[start],&nbsp; &nbsp; days: arr.slice(start + 1, end),&nbsp; }));};const array = ["January", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, "February", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]console.log(process(array));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答