AnswerBun.com

Optimize these 4 methods in 1 method

Stack Overflow Asked by Singh on October 3, 2020

const getDate = (id) =>{
  const userId =  info.find(user => user.id === id)
  return userId.date;
 }

 const getValueAtOne = (id) => {
   const userId =  info.find(user => user.id === id)
   if(userId?.value[0]){
   return userId?.value[0]
   }
  
 }
 const getValueAtTwo = (id) => {
  const userId =  info.find(user => user.id === id)
   if(userId?.value[1]){ 
   return userId?.value[1]
   }
 
 }
 const getAllValues = (id) => {
  const userId =  info.find(user => user.id === id)
   if(userId?.value) {
   const arrValue = userId?.roles.map((validData) => {
     return { value: validData, label:validData };
   });
   return arrValue;
 }
 }

I have these 4 methods, which I am calling from different places in my code.But i want to optimize my code and want all these methods in a single method, but I cant figure out the best way to do it. first method returns me the date, second one returns the value of array at position 1, third method returns value of array at position 2, and 4th method returns the all the value and convert it in object.

One Answer

You can return a single object like so:

const getAll = (id) => {
  const userId = info.find((user) => user.id === id);

  const [valueAtOne, valueAtTwo] = userId?.value ?? [];

  const allValues =
    userId?.value.roles.map((validData) => ({
      value: validData,
      label: validData,
    })) ?? [];

  return {
    allValues,
    valueAtOne,
    valueAtTwo,
  };
};

Correct answer by Dennis Vash on October 3, 2020

Add your own answers!

Related Questions

Appending a list in a list using a for loop

2  Asked on November 22, 2021 by syed-ahmed

 

Regular expression to find Specific character in a string

4  Asked on November 22, 2021 by user3061338

       

laravel count records based on each single date

1  Asked on November 22, 2021 by gulzar-ali

       

Change one property in CSS

2  Asked on November 22, 2021 by darek

 

Splitting values in a list and making variables of them

1  Asked on November 22, 2021 by premier12

     

JSX fragment has no corresponding closing tag

1  Asked on November 22, 2021 by chinwe-watkins

   

How to slow down window.location.href on AJAX request

3  Asked on November 22, 2021 by agiftel-longwave

     

Why list initialization disallow narrowing?

0  Asked on November 22, 2021 by alan-jian

   

How can i remove object from nested array?

2  Asked on November 22, 2021 by trajce12

 

How to save model architecture in PyTorch?

3  Asked on November 22, 2021

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP