skip to Main Content

I have an object with the following data.
I want to build a string from it but I need it to be in a specific order.

  const info = {
    first: 'John',
    last: 'Doe',
    middle: 'Henry',
    suffex: 'Sr',
  }

result = John Henry Doe Jr

Here is what I have but I’d like to get rid of the if/else

  const name= `${info.first}${
    info.middle ? ' ' + info.middle : ''
  } ${info.last}${info.suffix ? ' ' + info.suffix : ''}`

4

Answers


  1. You can use the ?. operator

    let info = {
        first: 'John',
        last: 'Doe',
        middle: 'Henry',
        suffix: 'Sr',
    }
    console.log(
      info?.first + " " + info?.middle + " " + info?.last + " " + info?.suffix
    )   // "John Henry Doe Jr"
    
    
    info = {
        first: 'Jane',
        last: 'Doe',
        middle: '',
        suffix: '',
    }
    console.log('>'+
      info?.first + " " + info?.middle + " " + info?.last + " " + info?.suffix
      +'<'
    );  // "Jane  Doe "
    Login or Signup to reply.
  2. Filter an array with conditional chaining

    const names = infos
      .map(info => [info?.first, info?.middle, info?.last,info?.suffix].filter(val=>val)
      .join(' ')
      );
    console.log(names)
    <script>
      const infos = [{
          first: 'John',
          last: 'Doe',
          middle: 'Henry',
          suffix: 'Sr'
        },
        {
          first: 'Jane',
          last: 'Doe',
        }
      ]
    </script>

    Alternatively use optional chaining, nullish coalescing operator and remove extra space using a RegExp

    const names = infos
      .map(info => `${info?.first ?? ''} ${info?.middle ?? ''} ${info?.last ?? ''} ${info?.suffix ?? ''}`
        .trim()
        .replace(/s+/g,' ')
      );
    console.log(names)
    <script>
      const infos = [{
          first: 'John',
          middle: 'Henry',
          last: 'Doe',
          suffix: 'Sr'
        },
        {
          first: 'Jane',
          last: 'Doe',
        }
      ]
    </script>

    Alternatively if the objects are in correct order

    You map to an array and filter on empty

    const names = infos
      .map(info => Object.values(info)
        .filter(val => val)
        .join(' ')
      );
    console.log(names)
    <script>
      const infos = [{
          first: 'John',
          middle: 'Henry',
          last: 'Doe',
          suffix: 'Sr'
        },
        {
          first: 'Jane',
          last: 'Doe',
        }
      ]
    </script>
    Login or Signup to reply.
  3. OR Operator in JavaScript

    You can use OR || in JavaScript.
    I wrote a little script and I used the OR operator.

    Working Code:

    let info = {
      first: 'John',
      last: 'Doe',
      middle: 'Henry',
      suffix: 'Sr',
    }
    
    let name = `${info.first} ${info.middle || ''} ${info.last} ${info.suffix || ''}`.trim();
    
    console.log("Result: " + name);
    
    
    info = {
        first: 'Jane',
        last: 'Doe',
        middle: '',
        suffix: '',
    }
    
    name = `${info.first} ${info.middle || ''} ${info.last} ${info.suffix || ''}`.trim();
    
    console.log("Result: " + name);

    I believe that this is the cleanest solution for your issue. Feel free to comment if you have any questions.

    Login or Signup to reply.
  4. I like keeping the code very clear with intention and what it is trying to do, as below:

    const info = {
      first: 'John',
      last: 'Doe',
      middle: 'Henry',
      suffix: 'Sr'
    };
    
    function getName(obj) {
      const result = [];
      if (obj.first) result.push(obj.first);
      if (obj.middle) result.push(obj.middle);
      if (obj.last) result.push(obj.last);
      if (obj.suffix) result.push(obj.suffix);
      return result.join(' ');
    }
    
    console.log(getName(info));

    Another way utilizing generators:

    const info = {
      first: 'John',
      last: 'Doe',
      middle: 'Henry',
      suffix: 'Sr'
    };
    
    function* getNames(obj) {
      if (obj.first) yield obj.first;
      if (obj.middle) yield obj.middle;
      if (obj.last) yield obj.last;
      if (obj.suffix) yield obj.suffix;
    }
    
    function getName(obj) {
      return [...getNames(obj)].join(' ');
    }
    
    console.log(getName(info));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search