I am new to React and trying to iterate over an object array where each object is of type Map with key, value pair. The structure is shown below,
EMP_CODE: {0: '001', 1:'002', 2: '003', .....}
EMP_NAME: {0: 'John', 1:'Davis', 2: 'Riya', .....}
EMP_DEPT: {0: 'Admin', 1:'HR', 2: 'HR', .....}
I am trying to build a network graph where the node attributes are supposed to be populated from the above objects. Sharing the code that i have developed but its not quite there. The nodes are getting created alright, issue is populating their attributes. I am trying to use a map but not sure if its the correct approach. Kindly assist.
const [graph, setGraph] = useState({
//nodeData.nodeData contains the above data
nodes: Object.entries(nodeData.nodeData).map((key, index) => ({
id: , // should come from EMP_CODE
label: , // should come from EMP_NAME
title: // should come from EMP_DEPT
// other attributes as needed (e.g., color, font, etc.)
})),
edges: []
});
3
Answers
Answer:
Assuming that all 3 object keys
EMP_CODE, EMP_NAME, EMP_DEPT
have the same amount of values.Code:
Explanation
EMP_CODE
,EMP_NAME
, andEMP_DEPT
.useState
to initialize thegraph
state.useEffect
to populate thegraph
state after the component mounts.Steps within
useEffect
Object.keys(nodeData.EMP_CODE).length
.Array.from
to create an array of nodes. The second argument toArray.from
is a mapping function, which accessesnodeData.EMP_CODE
,nodeData.EMP_NAME
, andnodeData.EMP_DEPT
by index.graph
state with the newly created nodes and an empty array for edges.Rendering the Graph
In the
return
statement, replace the placeholder with your actual network graph component or visualization logic, making use of thegraph
state. The example provided here uses a simplemap
to display the nodes as a list of headings and paragraphs.Notes:
EMP_CODE
,EMP_NAME
,EMP_DEPT
) always have consistent lengths to avoid indexing issues.node
objects with any additional attributes your network graph might need, such as styling properties or event handlers.This approach will correctly iterate over your object array and populate the attributes of each node accordingly.