I am trying to map a nested object in React. This is how my object currently looks like
"data": {
"user1": {
"Public": [
1,
0
],
"Team Only": [
1,
1
],
"All": [
1,
1
]
},
"user2": {
"Public": [
0,
0
],
"Team Only": [
0,
0
],
"All": [
0,
0
]
},
The way I am trying to map it is like this
const TableRows = (obj) => {
const userObject = Object.entries(obj);
const row = userObject.map((owner, mainIndex)=> {
return (
<TableRow key={console.log(`row-record-${owner[1]}`)} highlightOnHover={true}>
{Object.entries(owner[1]).map((value, index) => (
<TableCell
key={console.log(`column-value-${value}`)}
alignmentHorizontal={
tabsAlignment[props.metricComponent] &&
props.componentName != "Open_COE_Default"
? tabsAlignment[props.metricComponent][index]
: index != 0
? "center"
: ""
}
>
{owner[1]} // This prints out user1, 11,11 expected is user1, 1, 1
</TableCell>
))}
</TableRow>
);
});
return row;
};
The issue I am encountering is that when I do run this in the UI, the expected output should be something like
user1, 1, 1
user2, 1, 1
But instead the output turns out like this
user1, 11,11
user2, 22,22
Now I am unsure why it is taking the two separate values for 1 and 1 and then meshing them together. Is the way I am mapping not correct or am I not using the right keys for the map.
2
Answers
The issue in your code seems to be that you’re not accessing the individual elements of the value array correctly when rendering the
<TableCell>
component. Instead ofowner[1]
in the<TableCell>
component, you should usevalue[1][0]
for the first element andvalue[1][1]
for the second element, like this:EDITED CODE
This should render the expected output:
Note that
value[1]
is an array with two elements,value[1][0]
corresponds to the first element in the array(e.g., 1)
, andvalue[1][1]
corresponds to the second element in the array(e.g., 0)
.try this:
expected Output: