mardi 14 mai 2019

How to format a correct JSON using angular2-tree library

I'm using the angular2-tree component to generate a tree with checkboxes on every element. I would like to submit this tree to a web service.

I've already seen many posts like this and read the documentation, but I'm still not able to achieve the following.

I tried to do like this, following the suggestion by @eliseo on this comment:

collectSelectedNodes(tree: TreeModel) {
    let result: any = {}
    Object.keys(tree.selectedLeafNodeIds).forEach((x, index) => {
      let node: TreeNode = tree.getNodeById(x);
      if (node.isSelected) {
        if (node.parent.data.name) {
          if (!result[node.parent.data.name]) {
            result[node.parent.data.name] = {}
          }
          result[node.parent.data.name][index] = node.data.name;
        } else if (!result[index]) {
          result[index] = {}
        }
      }
    })

    this.selectedTree = result;
  }

And if I console.log() this.selectedTree I get this:

first-parent: {
    0: "abc", 
    1: "def", 
    2: "ghi", 
    3: "jkl", 
    4: "mno", 
    5: "pqr", 
    6: "stu"
}
second-parent: {
    7: "child1", 
    8: "child2"
}

Which is not properly a well formatted JSON.

What I want is something like this instead (even just the values without the keys would be OK):

"myTests": [
"first-parent": {
    0: "abc", 
    1: "def", 
    2: "ghi", 
    3: "jkl", 
    4: "mno", 
    5: "pqr", 
    6: "stu"
},
"second-parent": {
    7: "child1", 
    8: "child2"
}
]

How can I do this?




Aucun commentaire:

Enregistrer un commentaire