skip to Main Content

I implemented the idea of ​​OTP input in react and the result was an object as follows :

{input1: '8', input2: '8', input3: '8', input4: '8'}

How to convert this object into a continuous number as follows : 8888

thank you

5

Answers


  1. First of all, It is better to make OTP input field as a single field. Seems you are using 4 separate input fields.

    Anyway, the solution for your problem is, that you need to get Object values and join the object values as one string, Then convert it to a Number.

    NOTE: This solution assumes that the keys input1, input2, input3 and input4 are in the correct order.

    const obj = {input1: '8', input2: '8', input3: '8', input4: '8'};
    // Join object values and convert it to Number
    const numValue = Number(Object.values(obj).join(''));
    console.log(numValue);
    Login or Signup to reply.
  2. If you are not certain of the order of the keys then you could use

    const data = {
      input2: '2',
      input3: '3',
      input1: '1',
      input4: '4'
    };
    
    const sortedKeys = Object.keys(data).sort((a, b) => a.localeCompare(b, 'en', {
      numeric: true
    }))
    
    const code = sortedKeys.map(key => data[key]).join('');
    
    console.log(code);
    Login or Signup to reply.
  3. Since the entries will be alphabetically sortable we can do this if sort is needed

    const data = { input2: '2', input3: '3', input1: '1', input4: '4' };
    const result = Object.values(Object.fromEntries(Object.entries(data).sort())).join('');
    console.log(result); 

    Don’t do this, but it is really tempting to use with here (worth the mandatory downvotes 😉 )

    with (Object) var result = values(fromEntries(entries(data).sort())).join('');
    
    Login or Signup to reply.
  4. This question lacks precision…
    but assuming that

    • the property names are prefixed with the letters input followed by numbers between 1 and 4,
    • — without omitting a single one –,
    • Values are always an Ascii of a number from 0 to 9
    • result should be an integer value (and not a string)
    console.log(getVal({input1:'8',input2:'8',input3:'8',input4:'8'})); // 8888
    console.log(getVal({input1:'5',input4:'8',input2:'6',input3:'7'})); // 5678
    
    function getVal(obj)
      {
      let res = 0;
      for (let i=1; i<5;i++)
        {
        res += Number(obj[`input${i}`]) * 10**(4-i);
        }
      return res
      }
    Login or Signup to reply.
  5. Using an index to dynamically order the object keys correctly:

    const data = {
      input2: "2",
      input3: "3",
      input1: "1",
      input4: "4"
    };
    
    const result = Object.keys(data).reduce(
      (acc, _, i) => `${acc}${data[`input${i + 1}`]}`,
      ""
    );
    
    console.log(result); // 1234
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search