-1

I have an object

const arr = [{ x: 1, y: 2 }];

I want to use it in template literals, because of my use case but getting error, Suppose if we log this array using template literal like

console.log(`${arr}`);

We will get this error

array literal: This type can not be coerced to string

Any alternative solution that how can I use an array in template literals?

This is my use case I have a query

query {
      processes(
        page: 1,
        itemsPerPage: 100,
        filterBy: ${where}, // This is where I am getting this error, I want to pass an array here
      ) {
        id
        businessKey
        name
        processDefinition {
          name
        }
        createDate
        endDate
        tasks {
          id
        }
      }    
    }

But it gets converted to [Object Object]. I know there are limitations so if you can please suggest a better solution?

This is my where object

const where = [{ name: 'endDate', op: 'is null' }];
Amante Ninja
  • 647
  • 1
  • 6
  • 26

2 Answers2

0

If I understand correctly then what you are looking for is:

filterBy: ${JSON.stringify(where)}, 
HMR
  • 37,593
  • 24
  • 91
  • 160
0

I used this function

const formatArray = (array: Array<Object>) => {
    if (!array || array.length === 0) {
        return '[]';
    }
    const objs = array.map((obj) => {
        return Object.entries(obj)
            .map(([key, value]) => `${key}: "${String(value)}"`)
            .join(', ');
    });
    return `[{${objs.join('},{')}}]`;
};

and changed the query to

query {
      processes(
        page: 1,
        itemsPerPage: 100,
        filterBy: ${formatArray(where)} // This is where I am formatting my array
      ) {
        id
        businessKey
        name
        processDefinition {
          name
        }
        createDate
        endDate
        tasks {
          id
        }
      }    
    }

and it worked.

Amante Ninja
  • 647
  • 1
  • 6
  • 26