如何在字典内的列表内的字典中添加 ak 组键 + 值

时间:2021-07-29 09:59:55

标签: reactjs dictionary

我正在学习使用 ReactJs,但我不明白如何将键 + 值添加到包含在字典中的列表本身中包含的一组字典中......?

这里是数据:

export const datasTest = {
  labels: ["1", "2", "3", "4", "5", "6"],
  datasets: [
    {
      label: "# of Red Votes",
      data: [12, 19, 3, 5, 2, 3],
    },
    {
      label: "# of Blue Votes",
      data: [2, 3, 20, 5, 1, 4],
    },
    {
      label: "# of Green Votes",
      data: [3, 10, 13, 15, 22, 30],
    },
  ],
};

所以我想得到这个:

export const datasTest = {
  labels: ["1", "2", "3", "4", "5", "6"],
  datasets: [
    {
      label: "# of Red Votes",
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: "#c4b02e",
    },
    {
      label: "# of Blue Votes",
      data: [2, 3, 20, 5, 1, 4],
      backgroundColor: "#f3bf1d",
    },
    {
      label: "# of Green Votes",
      data: [3, 10, 13, 15, 22, 30],
      backgroundColor: "#fb601f",
    },
  ],
};

我添加了'backgroundColor: "#fb601f"'(手动:))

export const colorForLabel = [
  { label: "# of Red Votes", colour: "#c4b02e" },
  { label: "# of Blue Votes", colour: "#f3bf1d" },
  { label: "# of Green Votes", colour: "#fb601f" },
];

我写了这个,但我卡住了,我不知道如何附加我的新值:

  const [data, setDatas] = useState(
    CscDataService.getDatas()
  );

  function setColor() {
    {
      Object.entries(data["datasets"]).map(([key, values]) => {
        Object.entries(values).map(([key, value]) => {
          console.log(key + " " + value);
        });
      });
    }
  }

你能帮我一把吗?谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用功能状态更新来访问以前的状态并为每个对象添加背景颜色,例如:

export const colorForLabel = [
  { label: "# of Red Votes", colour: "#c4b02e" },
  { label: "# of Blue Votes", colour: "#f3bf1d" },
  { label: "# of Green Votes", colour: "#fb601f" },
];

function setColor() {
    setDatas((prevData) => {
        return {
            ...prevData,
            datasets: prevData.datasets.map(dataset => ({...dataset, backgroundColor: colorForLabel.find(({label}) => label === dataset.label).colour}))
        }
    })
}

答案 1 :(得分:1)

像这样的东西?

function setColor() {
  const updatedDatasets = data.datasets.map(dataset => {
    const { colour } = colorForLabel.find(({ label }) => label === dataset.label) || {};
    
    return {
      ...dataset,
      backgroundColor:colour 
    }
  });
  
  setDatas(currentData => ({
    ...curentData,
    datasets: updatedDatasets
  }));
}
};