代码之家  ›  专栏  ›  技术社区  ›  Shubham Singhvi

如何使用键作为另一个字符串打印对象值

  •  0
  • Shubham Singhvi  · 技术社区  · 4 年前

    我试图打印一个对象值,不是通过它自己的键,而是通过一个类似于键的字符串。不知怎么的,我使用useParams()字符串中的filter函数得到了密钥匹配,只剩下一步就可以得到我想要的输出了。

    import React from 'react';
    import { useParams } from 'react-router-dom';
    
    function MoreArticle() {
      const feed = {
        Fall : 'This is the Detailed description about season of Fall',
        Summer : 'This is the Detailed description about season Summer',
        Winter : 'This is the Detailed description about season Winter',
        Monsoon : 'This is the Detailed description about season Monsoon',
        Spring : 'This is the Detailed description about season Spring',
      };
    
      const { name } = useParams(); //Summer
      const seasons = Object.keys(feed);
    
      return (
        <div>
          <div>
            {seasons.filter(season => {
              console.log(feed.season);
              return(
                season == name && <div>{season}</div> //Returns Summer
                //season == name && <div>{feed.season}</div> 
                //How to return object description  👆🏻
                //by using something like this value |
              );
            })}
          </div>
        </div>
      );
    }
    
    export default MoreArticle;
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   Ian Rios    4 年前

    而不是使用 feed.season ,考虑使用括号表示法来针对特定的键值对,如下所示: feed[name]

    import React from 'react';
    import { useParams } from 'react-router-dom';
    
    function MoreArticle() {
      const feed = {
        Fall : 'This is the Detailed description about season of Fall',
        Summer : 'This is the Detailed description about season Summer',
        Winter : 'This is the Detailed description about season Winter',
        Monsoon : 'This is the Detailed description about season Monsoon',
        Spring : 'This is the Detailed description about season Spring',
      };
    
      const { name } = useParams(); //Summer
    
      return (
        <div>{feed[name]}</div>
      );
    }
    
    export default MoreArticle;
    

    点击此处查看更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors