首页 > 解决方案 > 与数组对象的键值映射

问题描述

我被困在用对象映射值。

我有对象数组

 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_ofdata那么我想展示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)

有人能帮我吗?

标签: javascriptarraysjsonreactjsecmascript-6

解决方案


你非常接近:

...
          <>
            {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"
};

推荐阅读