如何将数组转换为在第一个和最后一个数组元素上具有不同键的对象?

How do I convert an array to an object with different keys on the first and last array elements?

这是我目前尝试过的方法。

除了我无法弄清楚如何更改第一个和最后一个日期键之外,还有哪个有效?

 const dates: any = [
    '2020-06-24',
    '2020-06-25',
    '2020-06-26',
    '2020-06-27',
    '2020-06-28',
    '2020-06-29',
    '2020-06-30',
  ];

  const dateArrayToObject = () => {
    const dateObject = dates.reduce(
      (acc: string, date: string) =>
        Object.assign(acc, {
          [date]: { selected: true, marked: true },
        }),
      {}
    );

    return dateObject;
  };

在 reduce 方法中使用第三个参数 i(索引)。

 const dates = [
    '2020-06-24',
    '2020-06-25',
    '2020-06-26',
    '2020-06-27',
    '2020-06-28',
    '2020-06-29',
    '2020-06-30',
  ];

  const dateArrayToObject = () => {
    const dateObject = dates.reduce(
      (acc, date, i) =>
        Object.assign(acc, {
          [date]: { selected: true, marked: true, 
            first: i === 0,
            last: i === dates.length - 1 
            },
        }),
      {}
    );

    return dateObject;
  };
  
  console.log(dateArrayToObject())

我想这就是您所需要的。

const dates = [
    '2020-06-24',
    '2020-06-25',
    '2020-06-26',
    '2020-06-27',
    '2020-06-28',
    '2020-06-29',
    '2020-06-30',
  ];

var res= dates.reduce((acc, v, index, arr)=>{
  if(index === 0){
    acc = [...acc, {[v] : {startingDay: true, marked: true}} ]
  }else if(index === arr.length-1){
    acc = [...acc, {[v] : {ending: true, marked: true}} ]
  }else{
    acc = [...acc, {[v] : {selected: true, marked: true}} ]
  }
  return acc
},[])
console.log(res)

更新:如果你想将结果保存为对象而不是数组,你可以这样做:

 const dates = [
        '2020-06-24',
        '2020-06-25',
        '2020-06-26',
        '2020-06-27',
        '2020-06-28',
        '2020-06-29',
        '2020-06-30',
      ];

    var res= dates.reduce((acc, v, index, arr)=>{
     
           acc = index === 0? {...acc, ...{[v] : {startingDay: true, marked: true}} }
              : index === arr.length-1 ? acc = {...acc, ...{[v] : {ending: true, marked: true}} }
              : acc = {...acc, ...{[v] : {selected: true, marked: true}} }
      return acc
    },{})
    console.log(res)

使用 map 操作,您可以使用一些额外的道具来转换每个对象,例如 firstElementlastElement 并保留其余元素,因为它返回新的对象数组。

const dates = [
    '2020-06-24',
    '2020-06-25',
    '2020-06-26',
    '2020-06-27',
    '2020-06-28',
    '2020-06-29',
    '2020-06-30',
];

dates.map((value, index) => {
            const obj = {
                selected: true,
                marked: true
            };

            if (index == 0) {
                obj.firstElement = true;
                return obj;
            } 
            else if (index == dates.length - 1) {
                obj.lastElement = true;
                return obj;
            } 
            else {
                return obj;
            }
});