【问题标题】:How to dynamically convert Javascript Object Literal to String如何将Javascript Object Literal动态转换为String
【发布时间】:2020-06-20 20:53:27
【问题描述】:

我要转换

{
  ...
  {
    name: "Product 1",
    category: "Category 1"
  },
  {
    name: "Product 2",
    category: "Category 2"
  },
  ...
}

到

'Product 1 (Category 1)\r\nProduct 2 (Category 2)\r\n ... '

所以我的最终渲染看起来像:

Product 1 (Category 1)
Product 2 (Category 2)

谁能帮我解决这个问题?

【问题讨论】:

  • 您问题中的对象无效。对象中的每个元素都需要有一个键。外面的应该是一个数组吗?

标签: javascript string object tostring


【解决方案1】:

您可以使用map 和join:

const data = [
  {
    name: "Product 1",
    category: "Category 1"
  },
  {
    name: "Product 2",
    category: "Category 2"
  }
];

const res = data.map(({name, category}) => `${name} (${category})`).join('\r\n');

console.log(res);

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 2019-09-17
    • 2013-04-24
    • 2013-06-16
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多