manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format.

{"Drinks":[
{
"name":"name",
"discription":"discription",
"image":"image",
"ingredients":"['ingredients1', 'ingredients2']",
"instructions":"instructions",
"author":"author"
}
]}

currently, i am using the .map function to display all the content, but i am facing an issue when trying to extract and display ingredients separately. i tried nesting another .map function inside the first one, but unfortunately, i encountered this error:

TypeError: p.ingredients.map is not a function

here is the problematic code snippet

<ul>
<div className="grid">
{Drinks.map(p => (

  <a className="card_red">

    <h3>{p.name}</h3>

    <p>
      <b> {p.discription} <br/> <br/> </b>

        {
          p.ingredients.map(i => ( <b> {i} <br/> <br/> </b> 
          ))}

          <b> {p.ingredients} <br/> <br/> </b>

        <b> {p.instructions} <br/> <br/> </b>
        <b> {p.up_votes} <br/> <br/> </b>
        <b> {p.downvotes} <br/> <br/> </b>
        <b> {p.author} <br/> </b>

    </p>
  </a>
))}
</div>
</ul>

when the second .map function is removed, the output looks like this

i am aiming for an output similar to this

Answer â„–1

The 'ingredients' variable contains a String with double-quotes around the array in the JSON format, which is not valid JSON because the string values inside are delimited by single-quotes instead of double-quotes. To fix this issue, the correct format should be:

{"Drinks":[{
"name":"name",
"discription":"discription",
"image":"image",
"ingredients":["ingredients1", "ingredients2"],
"instructions":"instructions",
"author":"author"
}]}

If you are unable to resolve the issue at its source, one possible solution is to convert the 'p.ingredients' String into valid JSON by replacing any non-escaped single-quotes with double-quotes using the provided regular expression. This can be achieved as follows:

// Convert p.ingredients to valid JSON by replacing any (non-escaped) single-quotes with double-quotes 
// Regular expression adopted from: https://stackoverflow.com/a/8875837/1005404
const jsonizedIngredients = p.ingredients.replace(/([^'\\]*(?:\\.[^'\\]*)*)'/g, '$1\"');
// Parse the valid json
const ingredients = JSON.parse(jsonizedIngredients);
// Apply the mapping function
ingredients.map(...);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...

Can you explain how JSON and AJAX are different when used in conjunction with jQuery?

Is it true that JSON serializes all data, preventing problems with client-side issues like cross-browser support? I've found using AJAX with jQuery to be straightforward, but I'm still unclear about the differences. I have also come across anot ...

Scroll the table automatically when the currently selected row is the second-to-last row

Having trouble with a scrolling table issue. https://i.sstatic.net/PFyN3.png Upon page load, the first row (ROW 1) is automatically selected and highlighted. Clicking the next button selects and highlights the subsequent rows. However, once ROW >= 8 (e ...

What is the best method for integrating Bootstrap 5's Sass capabilities into a NextJS project?

Currently, I am in the process of working on a NextJS project that involves integrating Bootstrap 5. While I have past experience with Sass and NextJS, I seem to be encountering some difficulties when attempting to leverage Sass features within Bootstrap. ...

Incorporate an image into a Component template by utilizing a URL that is provided as a property of the Component in Vue and Vite

One of the challenges I faced was setting the 'src' attribute of an image in a Component's template from a property value. Initially, I attempted to do this as follows: Gallery View, where the Component is called multiple times <script s ...

Detecting collisions on a tile map using only JavaScript

Currently, I am developing a tile-based game using a traditional method (utilizing two for loops) and struggling with writing collision detection. I want the blue square to remain on the screen and appear on top of the tiles once the start button is clicke ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

My website code being stored in cache by Chrome (as well as other browsers)

Issue: I am facing an issue with hosting a widget on my client's website where the widget needs to be different for each page. To display the widget, the client embeds a script tag on their pages. This script is loaded on every page and the content ...

Exploring different sections of the website

I am looking to create a seamless navigation experience between controls on a webpage. Below is an example code snippet that outlines the functionality where a user can click on any component and be directed to another controller. Sample code: const app ...

I find that the Next.js useEffect function hinders my ability to smoothly navigate to a

I have a page displaying all the cards. When I click on a specific card, it redirects me to that card's details. The id is included in the URL. http://localhost:3000/cards/card?id=6539ccd487fa315543646ce5 I extract this id and retrieve the correspond ...

Ways to slow down page transition on NextJs

I'm currently working on securing my private pages using a HOC withAuth. While the protection is functioning correctly, I am looking to avoid users seeing a loading screen for a split second while the access token is being retrieved from local storage ...

Strategies for optimizing PPI and DPI in responsive design

Imagine having two monitors: one 15.5 inches with a resolution of 1920 x 1080 and the other 24 inches with the same resolution. The first monitor has a pixel density of around 72 PPI, while the second has around 90 PPI. If I apply a media query in CSS for ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

Configuring .env files for both production and development environments in Node.js

As I observed, there were various approaches to setting up environments in NodeJS - some seemed straightforward while others appeared more intricate. Is it possible to utilize package.json scripts to manage environment variables? If so, what is the best p ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

How can I manipulate image resolution and export images of varying sizes using Javascript?

I am new to using three js. I have successfully exported an image in png format using the WebGL renderer. However, when attempting to export the image in a different custom size resolution, the resolution does not change. How can I set the image resoluti ...

Storing Data in Nextjs: Ensuring Simple Data Persistence Across Route Changes

My current project involves allowing users to input images in the story route, which are then passed to the home route for display. Users can add as many images as they want, but I am facing a problem with retaining previously added images along with new o ...

Steps for inserting new rows into a table from text fields1. Begin

As someone who is brand new to jquery/html, I am eager to create a diary specifically for logging my long distance running times in a neat table format. Here's the HTML code I have been working on: <head> <title>Running Diary</titl ...