I have the following object:
const myObject = {
property1: ['apple', 'peach'],
property2: ['blue', 'red']
}
What I want to do is to create a list in a Table where I list on each row, the key name and right below, every elements of the corresponding array. Something like:
<li>property1</li>
<li>apple</li>
<li>peach</li>
<li>property2</li>
<li>blue</li>
<li>red</li>
Thank you all in advance.
It's not really clear whether you want a list or a table. But here's a quick example of a bulleted list using your data.
const { useEffect, useState } = React;
const data = {
property1: ['apple', 'peach'],
property2: ['blue', 'red']
};
// Simple function to mock an API response
function mockApi() {
return new Promise(res => {
setTimeout(() => {
res(JSON.stringify(data));
}, 2000);
});
}
// Create a list, and then `map` over the object
// entries. Use the key as a list heading, and then
// `map` over the values of the array to create a new list.
function Example() {
// Initialise state
const [state, setState] = useState(undefined);
// Get the data after two seconds
useEffect(() => {
mockApi()
.then(res => JSON.parse(res))
.then(data => setState(data));
}, []);
// If there is no state return "No data"
if (!state) return <div>No data</div>;
// Otherwise `map` over the object entries
// setting each key as the header, and `mapping`
// over the values array
return (
<ul>
{Object.entries(state).map(([key, arr]) => {
return (
<li>
{key}
<ul>
{arr.map(el => <li>{el}</li>)}
</ul>
</li>
);
})}
</ul>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Additional documentation
const obj = {
property1: ['apple', 'peach'],
property2: ['blue', 'red'],
}
const data = [];
Object.entries(obj).forEach(([key, values]) => {
data.push(key)
if (Array.isArray(values)) {
data.push(...values)
}
});
return (
<ul>
{data.map(str => <li>{str}</li>)}
</ul>
)
You can use something like this one. State is here.
const [records, setRecords] = useState(
[
{ id: 1, content: "property1"},
{ id: 2, content: "apple"},
{ id: 3, content: "peach"},
{ id: 4, content: "property2"},
{ id: 5, content: "blue"}
]);
Return method is here.
return (
<>
<ul>
{
records.map(r =>
<li> {r.id + " " + r.content} </li>
)
}
</ul>
</>
);