skip to Main Content

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


  1. Answer:

    const nodeData = {
      nodeData: {
        EMP_CODE: {
          0: '001',
          1: '002',
          2: '003',
        },
        EMP_NAME: {
          0: 'John',
          1: 'Davis',
          2: 'Riya',
        },
        EMP_DEPT: {
          0: 'Admin',
          1: 'HR',
          2: 'HR',
        }
      }
    };
    
    const data = {
      nodes: Object.entries(nodeData.nodeData["EMP_CODE"]).map(([index, empCode]) => ({
        id: empCode,
        label: nodeData.nodeData["EMP_NAME"][index],
        title: nodeData.nodeData["EMP_DEPT"][index],
        // other attributes... (color, font, etc.)
      })),
      edges: [] // Add your edges data here if needed
    };
    
    console.log(data)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.production.min.js"></script>
    Login or Signup to reply.
  2. Assuming that all 3 object keys EMP_CODE, EMP_NAME, EMP_DEPT have the same amount of values.

    const [graph, setGraph] = useState({
        nodes: Object.keys(nodeData.nodeData.EMP_CODE).map((key) => ({
          id: nodeData.nodeData.EMP_CODE[key],   // comes from EMP_CODE
          label: nodeData.nodeData.EMP_NAME[key], // comes from EMP_NAME
          title: nodeData.nodeData.EMP_DEPT[key], // comes from EMP_DEPT 
          // other attributes as needed (e.g., color, font, etc.)
        })),
        edges: []
    });
    
    Login or Signup to reply.
    1. Extract the Length: Determine the length of your data, assuming all arrays have the same length.
    2. Map the Values: Create the nodes array by mapping through the indices and populating the respective attributes.

    Code:

    import React, { useState, useEffect } from 'react';
    
    const nodeData = {
      EMP_CODE: {0: '001', 1: '002', 2: '003'},
      EMP_NAME: {0: 'John', 1: 'Davis', 2: 'Riya'},
      EMP_DEPT: {0: 'Admin', 1: 'HR', 2: 'HR'}
    };
    
    const YourComponent = () => {
      const [graph, setGraph] = useState({ nodes: [], edges: [] });
    
      useEffect(() => {
        const dataLength = Object.keys(nodeData.EMP_CODE).length;
    
        const nodes = Array.from({ length: dataLength }, (_, index) => ({
          id: nodeData.EMP_CODE[index],
          label: nodeData.EMP_NAME[index],
          title: nodeData.EMP_DEPT[index]
          // add other attributes as needed
        }));
    
        setGraph({ nodes, edges: [] });
      }, []);
    
      return (
        <div>
          {/* Your network graph component here, using the `graph` state */}
          {graph.nodes.map(node => (
            <div key={node.id}>
              <h3>{node.label}</h3>
              <p>{node.title}</p>
            </div>
          ))}
        </div>
      );
    };
    
    export default YourComponent;
    

    Explanation

    1. Initialization: Import React and necessary hooks.
    2. Node Data: Define your node data as an object with EMP_CODE, EMP_NAME, and EMP_DEPT.
    3. State Setup: Use useState to initialize the graph state.
    4. Effect Hook: Use useEffect to populate the graph state after the component mounts.

    Steps within useEffect

    1. Determine Data Length: Get the length of the data using Object.keys(nodeData.EMP_CODE).length.
    2. Create Nodes Array: Use Array.from to create an array of nodes. The second argument to Array.from is a mapping function, which accesses nodeData.EMP_CODE, nodeData.EMP_NAME, and nodeData.EMP_DEPT by index.
    3. Set Graph State: Set the 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 the graph state. The example provided here uses a simple map to display the nodes as a list of headings and paragraphs.

    Notes:

    • Ensure that your data (e.g., EMP_CODE, EMP_NAME, EMP_DEPT) always have consistent lengths to avoid indexing issues.
    • Extend the 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search