javascript - 与数组对象的键值映射
问题描述
我被困在用对象映射值。
我有对象数组
const data = [
{
_id: "535345345345345345311",
name: "Activity",
description: "this is activity",
filters: []
},
{
_id: "535345345345345345311",
name: "Activity",
description: "this is activity",
filters: [
{ _id: "49823476237423984", name: "ACTIVITY filter", origin: "ACTIVITY" }
]
}
];
在这里,就像那个对象数组有 user_of 那么它应该显示用户从对象读取数据。或者,如果对象上不存在数据,则按原样显示。就像上面的数组对象中有数据 example_of 一样,但对象中没有,则仅显示 example_of....
{
"user_of": "User",
"student_of": "Student",
"test_of": "TEST"
}
data
这是对象,现在如果user_of
我想User
在结果输出中显示。同样,如果我有student_of
,data
那么我想展示Student
下面是我试图实现这一目标的代码。
{data.filters.map((filter, index) => (
<>
{index < 2 && (
<span style={{ textTransform: "capitalize" }}>
{filter.origin.toLowerCase()}
{index === 0 && record.filters.length > 1 && <span>, </span>}
</span>
)}
</>
))}
{data.filters.length > 2 && (
<span> +{record.filters.length - 2} </span>
)}
这也是代码的工作示例https://codesandbox.io/s/hardcore-kilby-hhbon?file=/index.js
这就是我所期望的
基本上我想要的只是用该对象值替换该值(出于命名约定目的)。你可以在上面的代码框链接上看到这个,我很困惑。(JS世界的新手,以前用python)
有人能帮我吗?
解决方案
你非常接近:
...
<>
{index < 2 && (
<span style={{ textTransform: "capitalize" }}>
{objet[filter.origin]}
{index === 0 && record.filters.length > 1 && <span>, </span>}
</span>
)}
</>
...
我只是将其更改为返回{objet[filter.origin]}
objet
已定义,但您需要添加activity_of
const objet = {
user_of: "User",
student_of: "Student",
test_of: "TEST",
activity_of: "Activity"
};
推荐阅读
- javascript - 将鼠标移动添加到画布动画
- linux - 从bash中的变量打印倒数第二行
- bash - 使用 psql 命令从 postgres 传输与数据库所有权和使用 bash 的相关实体相关的所有内容
- azure - Azure 部署的机器人不响应
- html - Check_box_tag 输入标识
- java - 同步到 Java 中的 BigQuery“在数组外添加了重复记录”
- google-cloud-platform - 当我的 GCP 网络未称为“默认”时,使用 Halyard 将 GCP 配置为新 Spinnaker 安装中的云提供商时出现问题
- jmeter - JMeter - 从文件夹加载 XML 文件并在 HTTP 请求正文中使用
- java - 在 onClickListener 中显示 Toast
- acumatica - Acumatica 不允许用户输入特殊字符