JS3
JS3

Reputation: 1829

Using reduce and it caused an error that says "Cannot read property 'others' of undefined"

I'm using a reduce on this and it has an error that says: ""Cannot read property 'others' of undefined"

This is the codesandbox link: https://codesandbox.io/s/filter-sr3ci?file=/src/App.js:1408-1536

 let red = [...others1].reduce(
    (a, c) => (
      (a[c.["1"]?.others] = (a[c.["1"].others] || 0) + 1), a
    ),
    {}
  );

Below are the codes: import "./styles.css";

export default function App() {
  const data = [
    {
      displayName: "Person1",
      "1": { others: "", items1: { car: true, motor: true } }
    },
    {
      displayName: "Person2",
      "1": {
        others: "",
        items1: { car: true, motor: true, bike: true }
      },
      "2": { items2: { truck: true, bike: true }, others: "wire" }
    },

    {
      displayName: "Person3",
      "1": { others: "book", items1: { car: true, bike: true } },
      "2": {
        others: "wire",
        items2: { bike: true, motor: true, truck: true }
      }
    },

    {
      displayName: "Person4",
      "1": { others: "book", items1: { car: true, bike: true } },
      "2": { others: "", items2: { truck: true, bike: true } }
    },
    {
      displayName: "Person5",
      "1": { others: "", items1: { motor: true, car: true } },
      "2": {
        items2: { truck: true, bike: true },
        others: "fan"
      }
    },
    {
      displayName: "Person6",
      "2": {
        items2: { car: true, truck: true, motor: true },
        others: "fan"
      }
    },
    {
      "1": { others: "book", items1: { motor: true, car: true } },
      "2": {
        items2: { car: true, truck: true },
        others: "fan"
      },

      displayName: "Person7"
    }
  ];

  const others1 = data.filter((d) => d["1"]?.others !== "");

  // console.log(others1.length);

  let red = [...others1].reduce(
    (a, c) => (
      (a[c.["1"]?.others] = (a[c.["1"].others] || 0) + 1), a
    ),
    {}
  );


  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Upvotes: 0

Views: 54

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

It's because the object with the display name Person6 doesn't have a "1" object

When the Array.reduce function goes item by item, it could not find the "1" result in an undefined error.

So you just need to use optional chaining for it like so:

let red = others1.reduce(
  (a, c) => ((a[c["1"]?.others] = (a[c["1"]?.others] || 0) + 1), a),
  {}
);

Also, remove those dots before .["1"], since they are not valid, ['value'] is already equal to .value

Upvotes: 1

Related Questions