首页 > 解决方案 > 在 .map 函数中分隔数组

问题描述

我有一个导出 json 的数据库。导出的 json 看起来像这样。

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

使用 .map 函数,我可以打印出当前的所有内容,问题是我想分离出成分。我认为在第一个函数中使用另一个 .map 函数可以解决问题,但我不断得到

TypeError: p.ingredients.map is not a function

这是一些代码的麻烦

    <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>

女巫的输出是删除了第二个 .map 函数, 这里

我的预期输出看起来像这样

标签: javascriptnext.js

解决方案


您的“成分”是一个字符串,JSON 中的数组周围有双引号。此外,该字符串甚至不是有效的 JSON,因为其中的字符串值由单引号而不是双引号分隔。相反,它应该如下所示:

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

当您评论说您无法从源头上解决此问题时,您可能会做的是(您现在拥有的地方p.ingredients.map):

// Convert p.ingredients to valid JSON by replacing any (non-escaped) single-quotes with double-quotes 
// Search-regex is adopted from this anwer: 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(...);

推荐阅读