Natalia
Natalia

Reputation: 3

Convert JSON String to Object nodejs

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 class="image shopProduct" data-category=${product.category}><img src="data:image/png;base64, ${product.image}"/><h3 class="subtitle">${product.title} ${product.model}</h3><h5>${product.price} zł</h5><form action="/cart/products" method="POST"><input hidden value="${product.id}" name="productId" /><button class="button has-icon is-inverted">Dodaj do<i class="fa fa-shopping-cart"></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.

Upvotes: 0

Views: 854

Answers (2)

Tomasz Janczuk
Tomasz Janczuk

Reputation: 3248

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.

Upvotes: 0

Jack Barger
Jack Barger

Reputation: 224

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

Upvotes: 1

Related Questions