Home > Net >  why nested map showing repeated content in react
why nested map showing repeated content in react

Time:11-13

import "./styles.css";
const data = [
  {
    firstname: "junaid",
    lastname: "hossain",
    phones: [{ home: "015000" }, { office: "0177" }]
  },
  {
    firstname: "arman",
    lastname: "hossain",
    phones: [{ home: "013000" }, { office: "0187" }]
  }
];

export default function App() {
  return (
    <div className="App">
      <div className="users">
        {data.map((user, index) => {
          const { firstname, lastname } = user;
          return (
              <div key={index} className="user">
                <p>
                  name: {firstname} {lastname}
                </p>
                {user.phones.map((phone, i) => (
                  <div>
                    <p>home phone:{phone.home}</p>
                    <p>office phone:{phone.office}</p>
                  </div>
                ))}
              </div>
            );
        })}
      </div>
    </div>
  );
}

enter image description here

why a nested map showing repeated content? In this code, I don't want to show the empty office phone and home phone that I indicate in the picture by the red line. Now, what can I do to remove the extra content?

I would be very helpful if you tell me the answer.

CodePudding user response:

Only show a <p> if the value you're interpolating later exists.

<div>
  {phone.home && <p>home phone:{phone.home}</p>}
  {phone.office && <p>office phone:{phone.office}</p>}
</div>

CodePudding user response:

Solution-

<div className="users">
        {data.map((user, index) => {
          const { firstname, lastname } = user;
          return (
              <div key={index} className="user">
                <p>
                  name: {firstname} {lastname}
                </p>
                {user.phones.map((phone, i) => (
                  <div>
                    { !!phone?.home && <p>home phone:{phone.home}</p> }
                    { !!phone?.office && <p>office phone:{phone.office}</p> }
                  </div>
                ))}
              </div>
            );
        })}
      </div>

Explanation-

{ user.phones.map((phone, i) => (
    <div>
        <p>home phone:{phone.home}</p>
        <p>office phone:{phone.office}</p>
    </div>
))}

In this loop, you are looping through 'user.phones', and for the first(or each) object in data variable, that is equals to (for the first one)->

[{ home: "015000" }, { office: "0177" }] //length = 2

So logically, that map will run two times. For first time = { home: "015000" }, it will print,

    <p>home phone:015000</p>
    <p>office phone:undefined</p> // because in the first object, "office" key is not there

For second time = { office: "0177" },

    <p>home phone:undefined</p> // because in the second object, "home" key is not there
    <p>office phone:0177</p> 
  • Related