skip to Main Content

I have an object array:

cost = [{ 
id: 'cost01', 
client: { id: 'client01', first_name: 'Max', last_name: 'Xam'}, 
status: 'failed'
}]

I’m trying to create a new array using the object above. When an element is undefined, replace it with the string ‘N/A’

This is the code snippet:

const array = cost.map(
          (c: any) => ({
            data: [
              c.id,
              c.client.first_name +
                ' ' +
                c.client.last_name,
              c.total_price    // <--- this part is missing from cost 
                ? c.total_price
                : 'N/A',
              c.status
            ]
          })
        );

Notice that they array requires c.total_price, which the initial object cost does not have. So in this case c.total_price should be undefined and returns ‘N/A’
But on the created array, c.total_price is missing

Returned array:

['cost01', 'Max Xam', 'failed'] -> array length 3

Expected result:

['cost01', 'Max Xam', 'N/A', 'failed'] -> array length 4

How can I modify the code above to reach the expected result? Thanks in advance.

2

Answers


  1. You doesn’t need ternary operator(?).
    Just use nullish coalescing(??) or logical OR(||)

    const cost = [{ 
    id: 'cost01', 
    client: { id: 'client01', first_name: 'Max', last_name: 'Xam'}, 
    status: 'failed'
    }];
    
    const result = cost.map(c=>{
      const data = [c.id,
      c.client.first_name +' ' +c.client.last_name,
      c.total_price ?? "N/A",
      c.status,
      ]
      return {
        data
      }
    });
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; }
    Login or Signup to reply.
  2. Your code is correct. You can use ?? or ||, as Yuvraj mentioned.

    const cost = [{ 
    id: 'cost01', 
    client: { id: 'client01', first_name: 'Max', last_name: 'Xam'}, 
    status: 'failed'
    }]
    
    
    const array = cost.map(
              (c) => ({
                data: [
                  c.id,
                  c.client.first_name +
                    ' ' +
                    c.client.last_name,
                  c.total_price    // <--- this part is missing from cost 
                    ? c.total_price
                    : 'N/A',
                  c.status
                ]
              })
            );
    console.log(array)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search