Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - Iterating over JSON in React

I have following code:

export class Highlights extends React.Component {
    render() {
        return (
            <div>
                {JSON.stringify(this.props.highlights_data.data)}
            </div>
        )
    }
}

This prints out the following:

{"active":{"label":"Active","value":"12"},"automatic":{"label":"Automatic","value":"8"},"waiting":{"label":"Waiting","value":"1"},"manual":{"label":"Manual","value":"3"}}

How can I iterate over the highlights_data.data props to call another Component passing down label and value ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Except for @Dan's answer, I don't believe the other answers are any helpful/useful to you as they don't iterate through your JSON object.

To do this properly, you would need to iterate through each of your keys in your JSON object. There are a few ways you can do this, one of which is with Object.keys(). Like the code snippet below.

This solution iterates through each key in your JSON object and pushes it into an array. Once you have that array, you can iterate through it with map(), as you would normally, and pass your relevant props down to another child component.:

class MyApp extends React.Component {
  render() {
    var json = {"active":{"label":"Active","value":"12"},"automatic":{"label":"Automatic","value":"8"},"waiting":{"label":"Waiting","value":"1"},"manual":{"label":"Manual","value":"3"}};
    var arr = [];
    Object.keys(json).forEach(function(key) {
      arr.push(json[key]);
    });
    return <ul>{arr.map(item => <MyAppChild key={item.label} label={item.label} value={item.value} />)}</ul>;
  }
}

class MyAppChild extends React.Component {
  render() {
    return <li>{this.props.label + " - " + this.props.value}</li>;
  }
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...