Skip to content
Advertisement

Insert object if key doesn’t exist

I’m using recharts to add a new line to a chart where the key value of the object equals to a key value from another object. It works fine when it finds the key but the script doesn’t insert a new object if the key value is not found.

I have this array of objects in the state

{
  chartData: [
    { name: "100", line1: "332" },
    { name: "200", line1: "1235" },
    { name: "300", line1: "43534" },
    { name: "500", line1: "645324" },
    { name: "1000", line1: "345345" },
    { name: "2000", line1: "234234" },
    { name: "5000", line1: "654654" },
    { name: "10000", line1: "123" },
  ]
}

And this function that is adding a line where the values are the same

function addLine() {
  let newData = [
    { name: '100', line2: '6666' },
    { name: '230', line2: '2342342' },
    { name: '420', line2: '34234' },
    { name: '120', line2: '123656' },
    { name: '630', line2: '234245' },
  ];

  newData.map((io) => {
    this.setState((prevState) => ({
      chartData: prevState.chartData.map((el) =>
        el.name === io.name ? { ...el, line2: io.line2 } : { ...io, newData }
      ),
    }));
  });
}

How do I insert the values from newData that are not found in chartData?

An example could be found here https://codesandbox.io/s/recharts-toggle-legend-forked-i1qbd?file=/SampleChart.jsx:847-1310

Advertisement

Answer

newData.map((io) => {
  this.setState((prevState) => ({
    chartData: prevState.chartData.map((el) =>
      el.name === io.name ? { ...el, line2: io.line2 } : { ...io, newData }
    ),
  }));
});

Replace this with:

let chartData = this.state.chartData;
newData.map((io) => {
  const matchIdx = chartData.findIndex(el => el.name === io.name);
  if (matchIdx !== -1) {
    chartData[matchIdx] = {
      ...chartData[matchIdx],
      line2: io.line2
    };
  } else {
    chartData.push(io);
  }
});

this.setState({ chartData: chartData });
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement