反应如何将字符串转换为对象属性

时间:2018-12-19 01:27:09

标签: reactjs react-redux

在React项目中,我想使用通过props传递的字符串变量来动态访问对象属性名称。我可以将值作为字符串传递;但是,当我尝试使用它来访问对象属性时,它不起作用。

这是一个例子:

ggplot(data = data, aes(x = key, y = value, fill = key)) + 
    stat_summary(fun.y = "mean", geom = "bar", width = 0.5) +
    stat_summary(aes(label = round(..y.., 1)), 
                 fun.y="mean", geom="text", vjust = -0.5) +
    geom_hline(yintercept = 3, linetype = "solid", 
               color = "red", size = 1.5, alpha = 0.25) +
    # limit the vertical space to 1 to 4, but keep the data
    coord_cartesian(ylim = c(1, 4)) +
                       # set ticks at 1, 2, 3, 4
    scale_y_continuous(breaks = c(1:4),
                       # label them with names
                       labels = c("Strongly Disagree", "Disagree",
                                  "Agree", "Strongly Agree"))

我访问这样的标题const passedField = 'title'; // this comes from props const book = { title: 'Sample title', content : 'some content' }; book.passedField; // returns undefined

我想像book.title一样访问它,但是在控制台上却未定义。

我该如何实现?

3 个答案:

答案 0 :(得分:2)

您所使用的称为dot notation属性访问器。您需要使用一个bracket notation属性访问器。

book.titlebook['title']是相同的,这意味着您可以将title分配给变量,并像这样使用变量名。

const passedField = 'title';
book[passedField]; // same as book['title']

您可能只熟悉bracket notation和Array,例如myArray[0],但是它们也可以与对象一起使用! (因为JavaScript中的数组实际上是对象)

解决方案

const books = [
  {
    title: 'The Art of War',
    contents: 'An ancient Chinese military treatise dating from the Spring and Autumn Period'
  },
  {
    title: 'Winnie the Pooh',
    contents: 'Pooh is naive and slow-witted, but he is also friendly, thoughtful, and steadfast.'
  }
]

class Book extends React.Component {
  constructor(props) {
    super(props);
    this.findBookByFilter = this.findBookByFilter.bind(this);
  }
  
  findBookByFilter() {
    let result = null
    if (books) {
      const {passedFilterField, filterText} = this.props;
      
      result = books.filter(book => {
        return book[passedFilterField].toLowerCase().includes(filterText.toLowerCase());
      }).map(book => <p>{book.title}</p>)
    }
    return result;
  }
  
  render () {
    return this.findBookByFilter();
  }
}

class App extends React.Component {
  render() {
    return (
      <Book
        passedFilterField='contents' 
        filterText='thoughtful'
      />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

注释

  • 我将您的{book && book.filter}逻辑移到了名为findBookByFilter的函数中
  • 我在includes中使用了indexOf而不是filter
  • 我使用了this.props的解构分配
  • 我返回匹配的标题,而不是出于演示目的<Link />

文档

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

答案 1 :(得分:2)

book.passedField将返回不确定的,因为passedField中没有book。而是使用如下的括号符号

const book = { title: 'abc', pages: 350 };
const passedField = 'pages';

console.log(book[passedField])

答案 2 :(得分:1)

您可以使用book[passedField]

访问对象属性