I want to render a Object .
My Object is:
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
I want it to render as:
id is 1 ; name is ABC
id is 3 ; name is DEF
I want to make this object in a function and is called in render function.
Data is an object so directly we can't use map on that, so use Object.keys or Object.entries to get the array first, then use map
on that to create ui items.
Using Object.keys:
_renderObject(){
return Object.keys(ObjectTest).map(obj, i) => {
return (
<div>
id is: {ObjectTest[obj].id} ;
name is: {ObjectTest[obj].name}
</div>
)
})
}
Using Object.entries:
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
class App extends React.Component{
_renderObject(){
return Object.entries(ObjectTest).map(([key, value], i) => {
return (
<div key={key}>
id is: {value.id} ;
name is: {value.name}
</div>
)
})
}
render(){
return(
<div>
{this._renderObject()}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'/>
Check this answer also: How to loop an object in ReactJS?
I wonder why it seems that almost every one is using Object.keys!
Object.values(ObjectTest).map((row_, index) =>
<tr>
{Object.values(row_).map(item => <td>{item}</td>)}
</tr>
)}
Sample Data:
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
all these mappings... Bruh. Use "pre" tag with JSON.stringify
<pre>
{JSON.stringify(yourdataobject, null, 2)}
</pre>
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
render(){
return (
<div>
Object.keys(ObjectTest).map( (key)=> {
return <div>
<span>"Id is:"{key}<span>
<span>"Name is:"{ObjectTest[key].name}<span>
</div>
})
</div>
)
}
In react you can render your wish answer in browser screen by below code
import React from 'react';
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
class App extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div>
{
Object.keys(ObjectTest).map((value,index)=>{
<p>id is {ObjectTest[value].id} ; name is {ObjectTest[value].name}</p>
});
}
</div>
);
}
}
export default App;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With