Home > Software design >  Convert JSON String to Object nodejs
Convert JSON String to Object nodejs

Time:11-06

products.json: {"model": "PLM-7-P-21","category":["classic","new"],"fabric":["white","beech","glass"], "shine": "false","size": "45x25","bulb": 2, "id": "5cfa55c5"},`

and then I want to use category and fabric as data-category:const layout = require('../layout');module.exports = ({ products }) => {const renderedProducts = products.map(product => {return <div data-category=${product.category}><img src="data:image/png;base64, ${product.image}"/><h3 >${product.title} ${product.model}</h3><h5>${product.price} zł</h5><form action="/cart/products" method="POST"><input hidden value="${product.id}" name="productId" /><button >Dodaj do<i ></i></button></form></div>;}).join('\n');` but then I have got a string data-category="classic, new" but I want to get data-category="classic new" without comma... I would be grateful for your help.

CodePudding user response:

I think you are looking for JSON.parse which will convert string data directly to a JSON object, so long as the string is in valid syntax.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

CodePudding user response:

Instead of

data-category=${product.category}

do

data-category=${product.category.join(' ')}

You are getting the comma because the default serialization of an array separates elements with a comma.

  • Related