为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2023-09-28 15:38:38
我有一个数组,我想将此数组转换为单独的对象,很高兴帮助我,谢谢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]   }]
查看完整描述

1 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

    首先找出数组中字符串的索引,以便可以拆分数组。


const process = (arr) => {

  const result = [];

  let last = -1;

  for (let i = 0; i <= arr.length; i++) {

    if (typeof arr[i] === "string" || !(i in arr)) {

      if (last !== -1) {

        result.push([last, i]);

      }

      last = i;

    }

  }


  return result.map(([start, end]) => ({

    month: arr[start],

    days: arr.slice(start + 1, end),

  }));

};


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


查看完整回答
反对 回复 2023-09-28
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信