V
V
Vasyl Kovbassa2017-07-04 19:26:07
JavaScript
Vasyl Kovbassa, 2017-07-04 19:26:07

What is the best way to work with data array?

Help, because I have a crisis. I can’t catch up with how to implement this:
From the server, from MongoDb, an array of objects of the following form comes:

let data = [
    {
      name: 'string',
      val1: int,
      val2: int,
      nodes: [
          {
           name: 'string',
           val1: int,
           val2: int,
           nodes: [  ...  ]
          }, 
          {
          // ... 
          }
      ]
    },
    {
    // ...
    }
]

nesting level of child arrays is not limited. That is, each node can have any number of its child nodes, which in turn are their own. Based on this array of data, you need to make a React app with the ability to add new nodes and subnodes in the form of a tree and summing child values ​​in parent components:
_'${name} | ${val1} | ${val2= val1+childs val2}'
 |___ '${name} | ${val1} | ${val2=val1+childs val2}' // child
 |_____ .....

How to correctly bypass such an array and use the UI to edit, add and remove nodes?
Tell me who can. Thanks in advance!
PS: This is my first exposure to React.js, but I've got to know the basic principles.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-07-05
@movasyl

This is a normal recursive tree traversal. Adding\removing\editing will depend on how (and where) you store the data - flux\redux\whatever. In the case of redux, I would store the tree in state in a flat form (you will need id, but I think that with mongo this is not a problem).
You can display the tree like this:

const MySuperTree => (props) => (
  <ul>{props.nodes.map(node => <TreeNode {...node} />)}</ul>
)

class TreeNode extends PureComponent { 
  render() {
    const { name, val1, val2, nodes } = this.props
    return (
      <li>
        <b>{name}  | {val1} | {val1+getValFromChild(childs)} {val2}</b>
        {nodes && nodes.length > 0 && (
          <MySuperTree nodes={nodes} />
        )}
     </li>
    )
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question