0

I have this object:

const plans = tests: {
    [TestID: string]: {
        test_id: number;
        test_name: string;
        cases: {
            [caseID: string]: {
                case_id: number;
                case_name: string;
            };
        };
    };
}

I converted the object to an array ( const plansArray = Object.values(plans);) so that I can map it in my react code. I want to know if there is a way to optimize or find a better way to do what I am doing below:

{plansArray &&
        plansArray.map((Plan) => (
          <div key={Plan.test_id}>
            //The NestedDropdown is just an accordion - the title prop will display on the accordion
            <NestedDropdown
              title={Plan.test_name}
            >
              // This is my concern, is there a better way to handle this?
              {Object.values(Plan.cases).map((cases) => (
                <NestedDropdown
                  key={cases.case_id}
                  title={`- ${cases.case_name}`}
                ></NestedDropdown>
              ))}
            </NestedDropdown>
          </div>
        ))}

As you can see I am mapping over the Plan to access the nested cases object. I there a way to only map once?

3
  • Perhaps you could flatten the object. Commented Jun 21, 2021 at 15:08
  • You could probably do as yudhiesh says, but isn't this a case of premature optimization? I wouldn't say nested loops are bad per se. It depends on the situation whether you should use them. If you're not experiencing problems with the approach you could also just keep it this way. Commented Jun 21, 2021 at 15:13
  • @BasvanderLinden I am thinking about scale. I am expecting this to get larger over time. Commented Jun 21, 2021 at 15:25

1 Answer 1

3

There isn't any reason to "simplify" this. Given the shape of your object, it's already as "simple" as it can get.

Performance wise, you really only have to worry about multiple nested loop when those are looping over the same data. But in your case, one loop maps the the list of plans, and the other loop maps the list of cases in each plan. Given this structure, mapping over one, then the other is going to be the fastest approach, especially since the actual elements are nested inside each other.

I'm not sure what problem you think you have, but I believe you already have the optimal strategy here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.