Reputation: 382
My local JSON file is as follows
[
{ "time": "2017", "Id": 1, "value": 40 },
{ "time": "2018", "Id": 1, "value": 65 },
{ "time": "1018", "Id": 1, "value": 34 }
]
I imported the JSON like:
import * as readings from '../data/readings';
And I want to render my data in a list in a React component.
This is what I have been tried:
import * as readings from '../data/readings';
class Table extends Component {
render (){
const data = Object.keys(readings).map((row, index) =>
<li key={index}> {row} </li>);
return (
<div>
<ul>
{data}
</ul>
</div>
);
}
}
export default Table;
After rendering this component, I will see "default" on the screen but my aim is to have each object in one row like:
Can someone tell me what I am doing wrong? I've read a lot of related question but I could not relate.
Edit:
My data is an array itself but the import gives it like an object. That's why I use Object.keys
and not readings.map
Upvotes: 1
Views: 221
Reputation: 3899
readings
is itself an array so that is what you want to map over: readings.map()
. The items in it are the objects you want to display, so there is where you want to use Object.keys()
. Since you want to use the values as well, Object.entries()
is slightly more readable.
Also, you are importing data from a JSON file so you should import the data as though it was a default export. You should explicitly specify the .json
file type since it is not a .js
file.
import readings from '../data/readings.json';
class Table extends Component {
render() {
const data = readings.map((reading, index) => {
const readingData = Object.entries(reading).map((k, v) => <span>{k}: {v}</span>);
return <li>{readingData}</li>;
};
return (
<div>
<ul>
{data}
</ul>
</div>
);
}
}
export default Table;
Upvotes: 1
Reputation: 6057
Your readings
data is already an Array
. You can directly use map
on it.
import * as readings from '../data/readings';
class Table extends Component {
render (){
const readingsArray = Object.keys(readings).map(key => readings[key]);
const data= readingsArray.map(obj => <li>{JSON.stringify(obj)}</li>);
return (
<div>
<ul>
{data}
</ul>
</div>
);
}
}
export default Table;
Upvotes: 0
Reputation: 176
Your readings
is not an object, it's an array! So, what you should do is to iterate over it, and for every inside object, do the process of Object.keys(readings).map()
import * as readings from '../data/readings';
class Table extends Component {
render (){
const data = readings.map((row, index) =>
<li key={index}>
{
Object.keys(row).map(e =>
`${e[0]: e[1],} `
}
)
</li>
)
return (
<div>
<ul>
{data}
</ul>
</div>
);
}
}
export default Table;
Upvotes: 0