Reputation: 107
myObj = {name: 'Alice', age: '19', weight: 52}
I wanted all the key and values inside the object to be rendered to one label and input respectively.
I have tried it using Object.entries
but then key and values cannot be separated. Any suggestion for doing this? Thank you
Upvotes: 0
Views: 623
Reputation: 17598
I don't know what kind of problem do you have with Object.entries
but it can be used in your situation:
class App extends React.Component {
state = {
myObj: {
name: 'Alice', age: '19', weight: 52
},
}
render() {
const { myObj } = this.state;
return (
<div>
{
Object.entries( myObj ).map( ( [ key, value ] ) =>
<div key={key}>
<label>{key}</label>
<input placeholder={value} />
</div>
)
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>
Upvotes: 3
Reputation: 6587
You can do it with Object.keys
too. It will iterate through object keys
class App extends React.Component {
state = {
myObj: {
name: 'Alice', age: '25', weight: 55
},
}
render() {
const { myObj } = this.state;
return (
<div>
{
Object.keys(myObj).map((key,index) =>
<div key={index}>
<label>{key}</label>
<input placeholder={this.state.myObj[key]} />
</div>
)
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>
Upvotes: 4