javascript - 在 .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 函数, 这里
我的预期输出看起来像这样
解决方案
您的“成分”是一个字符串,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(...);
推荐阅读
- promise - 云函数-firestore:如何从 2 个查询中获取令牌
- angular - 内容安全策略 (CSP) 不适用于 style-src self
- java - 从卡片组(ArrayList)中查找卡片并打印其索引
- java - 如何检查 i18n 消息资源参数是否为空?
- spring - CriteriaQuery 等效于 MySQL 中的条件和查询?
- bitbucket - Bitbucket 无法持久化条目:API_ERROR:找不到分支
- vue.js - 在 VS Code 的 vue 项目中使文件在 chrome 中可用
- node.js - 如何使不和谐机器人发出-100到100之间的随机数
- angular - Kendo 表单控件适用于一个组件但不适用于其他组件
- java - 我试图找出一个数字是否是素数,并且错误抛出“参数类型 int int 的运算符 && 未定义”