最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: Variable after keyname in map function - Stack Overflow

programmeradmin1浏览0评论

Hi I have this Code with objects:

const data = [{
item1: {
    ans1: "Ich",
    ans2: "Du",
    ans3: "Jemand",
    ans4: "Egal",
    correct: 3,
    quest: "Wer hat die Kokosnuss geklaut?"
}];

and this:

    render() {
    const hereGoesMyLevelNum = this.state.level;
    const answers = data.map((answer) => {
        return (
          <ul>
              <li>{answer.item1.ans1}</li>
              <li>{answer.item1.ans2}</li>
              <li>{answer.item1.ans3}</li>
              <li>{answer.item1.ans4}</li>
          </ul>
        )
    });

    return (
      <div className="App">
         <ul>{answers}</ul>
      </div>
    );}} export default App;

I want to get the "answers.items" dynamically by passing the level number from the state to it. Something like:

{answer.item{hereGoesMyLevelNum}.ans1}

Can you help me please? :)

Hi I have this Code with objects:

const data = [{
item1: {
    ans1: "Ich",
    ans2: "Du",
    ans3: "Jemand",
    ans4: "Egal",
    correct: 3,
    quest: "Wer hat die Kokosnuss geklaut?"
}];

and this:

    render() {
    const hereGoesMyLevelNum = this.state.level;
    const answers = data.map((answer) => {
        return (
          <ul>
              <li>{answer.item1.ans1}</li>
              <li>{answer.item1.ans2}</li>
              <li>{answer.item1.ans3}</li>
              <li>{answer.item1.ans4}</li>
          </ul>
        )
    });

    return (
      <div className="App">
         <ul>{answers}</ul>
      </div>
    );}} export default App;

I want to get the "answers.items" dynamically by passing the level number from the state to it. Something like:

{answer.item{hereGoesMyLevelNum}.ans1}

Can you help me please? :)

Share Improve this question asked Sep 30, 2017 at 20:27 user3708479user3708479 91 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Use square brackets like this

{answer["item"+hereGoesMyLevelNum].ans1}

You can use Object.keys() to dynamically get property names from your object.

Example

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

If you only have one property in your object you can do something like below.

const answers = data.map((answer) = > {

  // Gets the first property name
  const itemLevel = Object.keys(answer)[0];

  // Loops through the inner properties and returns list items
  const listItems = Object.keys(answer[itemLevel]).map((d) => {
    if (d.startsWith('ans')) return (<li>{answer[itemLevel][d]}</li>);
  });

  return (<ul>{listItems}</ul>);
});

You can use the Es6 Computed property keys syntax (with bination of ES6 Template literals).

Computed property keys

const id = 1;
const myKeyName = 'key' + id;
myObject[myKeyName]

Combined with Template literals

const id = 1;
const myKeyName = `key${id}`;
myObject[myKeyName]

Running Example:

const data = [
  {
    item1: {
      ans1: "Ich",
      ans2: "Du",
      ans3: "Jemand",
      ans4: "Egal",
      correct: 3,
      quest: "Wer hat die Kokosnuss geklaut?"
    }
  }
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      level: 1
    };
  }


  render() {
    const hereGoesMyLevelNum = this.state.level;
    return (
      <div>
        {
          data.map((answer) => {
            const lvlAnswer = `item${hereGoesMyLevelNum}`;
          return (
            <ul>
              <li>{answer[lvlAnswer].ans1}</li>
              <li>{answer[lvlAnswer].ans2}</li>
              <li>{answer[lvlAnswer].ans3}</li>
              <li>{answer[lvlAnswer].ans4}</li>
            </ul>
          )
        })
       }
      </div>
    );
  }
}

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

发布评论

评论列表(0)

  1. 暂无评论