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

1 thought on “Insert object if key doesn't exist”

  1. Try this, and inform me if it serves the result that you need

    addLine() {
        const newData = [
          { name: "100", line2: "6666" },
          { name: "230", line2: "2342342" },
          { name: "420", line2: "34234" },
          { name: "120", line2: "123656" },
          { name: "630", line2: "234245" }
        ];
        const modifiedData = [...newData, ...this.state.chartData];
        this.setState({
          chartData: modifiedData.filter((data, index, array) => 
            array.findIndex(({ name }) => name === data.name) === index
          )
        }); // Simply adding both arrays together and then filtering them
      }
    

    enter image description here

    Reply

Leave a Comment