向 javascript 对象添加动态键和动态值

问题描述 投票:0回答:1

我想从打字稿中的以下函数发回这样的对象:

    marked = {
      '2024-08-21': {
        dots:[food, recycling]
      },
      '2024-08-22': {
        dots:[food, recycling]
      }
    }

这是我目前所拥有的。

function addKeysAndValuesDynamically(days: string[]): any {
  var marked = {};
  const food = {key: 'food', color: 'brown'};
  const recycling = {key: 'recycling', color: 'green'};
  days.forEach((day: string) => {
    marked[day]['dots'] = food, recycling;
  });
  return marked;
}

var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = addKeysAndValuesDynamically(days);
console.log(`marked = ${marked}`);

我希望它返回“标记”的对象,如上所示,但我收到错误:

TypeError: Cannot set property 'dots' of undefined

typescript react-native
1个回答
0
投票

我假设您刚刚从 javascript 转向打字稿,因为您试图避免使用类型,这是您可以使用接口来做到这一点的一种方式:

interface KeyColor {
    key: string;
    color: string;
}

interface Marked {
    [day: string]: {
        dots: [KeyColor, KeyColor]
    }
}

function addKeysAndValuesDynamically(days: string[]): Marked {
  const marked: Marked = {};
  const food = {key: 'food', color: 'brown'};
  const recycling = {key: 'recycling', color: 'green'};
  days.forEach((day: string) => {
    marked[day] = { dots: [food, recycling] }
  });
  return marked;
}

var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = addKeysAndValuesDynamically(days);
console.log(marked); // you have to log it this way to view content
© www.soinside.com 2019 - 2024. All rights reserved.