简体   繁体   中英

How to dynamically convert Javascript Object Literal to String

I want to convert

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

to

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

So my final render looks like:

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

Can anyone help me with this?

You can use map and 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM