Home > front end >  How to traverse a node tree and modify its structure & value
How to traverse a node tree and modify its structure & value

Time:11-04

Here is My input. Some of its nodes consist of downlines which have other multiple nodes.

data = [
  {
    "user_id": "1",
    "username": "johndoe001",
    "amount": "0.00",
    "downlines": [
      {
        "user_id": "2",
        "username": "j001-01",
        "amount": "1.00",
        "downlines": []...

How can I transform it into output as below?

[
    {
      "key": "1",
      "label": "johndoe001 (0.00)",
      "nodes": [
        {
          "key": "2",
          "label": "j001-01 (1.00)",
          "nodes": []...

I am able to complete partially using simple string replace, but I failed to modify the label value to be a combination of username and amount. I also fail to remove unneeded keys like amount after this.

let stringJson = JSON.stringify(data);
stringJson = stringJson.replace(/downlines/g, 'nodes');
stringJson = stringJson.replace(/username/g, 'label');
stringJson = stringJson.replace(/user_id/g, 'key');
let tmpTree = JSON.parse(stringJson);

CodePudding user response:

This becomes pretty simple with a recursive function:

const data = [
  {
    "user_id": "1",
    "username": "johndoe001",
    "amount": "0.00",
    "downlines": [
      {
        "user_id": "2",
        "username": "j001-01",
        "amount": "1.00",
        "downlines": []
      },
    ]
  },
];

function rename(downlines) {
    return downlines.map(({ user_id, username, amount, downlines }) => ({
        key: user_id, // rename user_id to key
        label: `${username} (${amount})`, // format label
        nodes: rename(downlines), // now do the same to the rest
    }));
}

console.log(rename(data));

See destructuring if you are confused about the ({ ... }) => syntax.

  • Related