Jaimouest
Jaimouest

Reputation: 35

How to add ak set of keys + values in dictionaries inside a list inside a dictionary

I'm learning to use ReactJs but I don't understand how I could add a key + value to a set of dictionaries contained in a list itself contained in a dictionary ...?

here are the datas :

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],
    },
  ],
};

So i would like to get this :

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",
    },
  ],
};

I added 'backgroundColor: "#fb601f"' (by hand :))

with

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

I writted this, but i'm stuck, i don't know how to append my new values :

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

Can you give me a hand ? Thanks

Upvotes: 1

Views: 125

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

You can use functional state update to get access to the previous state and add backgroundColor to each object like:

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

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

Something like this ?

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

Upvotes: 1

Related Questions