【问题标题】:array literal: This type can not be coerced to string数组字面量:此类型不能强制转换为字符串
【发布时间】:2018-02-08 21:54:08
【问题描述】:

我有一个对象

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

我想在模板文字中使用它,因为我的用例但出现错误,假设我们使用模板文字记录这个数组

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

我们会得到这个错误

array literal: This type can not be coerced to string

我如何在模板文字中使用数组的任何替代解决方案?

这是我的用例我有一个查询

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
        }
      }    
    }

但它被转换为[Object Object]。我知道有一些限制,所以如果你能提出一个更好的解决方案?

这是我的 where 对象

const where = [{ name: 'endDate', op: 'is null' }];

【问题讨论】:

  • 那么,where 是什么?
  • 对不起,我已经更新了代码
  • 模板文字用于字符串。如果你想要一个对象,为什么不直接分配……对象呢? filterBy: where,或者如果您需要获取副本:filterBy: [Object.assign({}, where[0])]...
  • 因为我需要在filterBy中传递数组
  • 那么传递数组?模板文字用于获取字符串。所以如果你需要一个数组,那么不要使用模板文字。

标签: javascript ecmascript-6 template-literals


【解决方案1】:

如果我理解正确,那么您正在寻找的是:

filterBy: ${JSON.stringify(where)}, 

【讨论】:

  • 它会生成这个数组 [{ "name": "endDate", "op": "is null" }],我不想要 :(
  • @sbs filterBy: ${JSON.stringify(where[0])},?
【解决方案2】:

我用过这个功能

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('},{')}}]`;
};

并将查询更改为

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
        }
      }    
    }

它成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多