Change the key value in the tree structure

const target = [{
    "title": "",
    "value": "",
    "children": [{
        "title": "",
        "value": "361,123",
        "children": null
      },
      {
        "title": "",
        "value": "361,123",
        "children": null
      },
      {
        "title": "",
        "value": "361,123",
        "children": null
      },
      {
        "title": "",
        "value": "361,123",
        "children": [{
            "title": "",
            "value": "361,123",
            "children": null
          },
          {
            "title": "",
            "value": "361,123",
            "children": null
          }
        ]
      }
    ]
  },
  {
    "title": "",
    "value": "",
    "children": null
  }
]

has the following data structure, how to change the title into name, how to use recursive writing can not come around, please expert advice.

May.13,2022

function trans (data) {
  data.forEach(item => {
    item.name = item.title // titlename
    delete item.title // title

    item.children && trans(item.children) // children
  })
}

trans(target)
console.log(target)



replace(target);

function replace(target) {
  if (target instanceof Array) {
    target.forEach(element => {
      replace(element);
    });
  } else if (target && typeof target === "object") {
    Object.keys(target).forEach(key => {
      if (target[key] && typeof target[key] === "object") {
        replace(target[key]);
      }
      if (key === 'title') {
        target['name'] = target[key];
        delete target['title'];
      }
    });
  } else {
    return;
  }
}
console.log(target);

first converts to a JSON string, then replaces all title attributes of the string, and finally converts it to a string.

but you need to change const target to let target

JSON.stringify(target).replace(/"title":/g,'"name":'))

if you don't like this method, you can choose recursion to solve it.


there are so many answers, all of which are good answers, but it is better to teach people to fish than to teach people to fish. I can briefly share my own experience in writing recursive code to prevent ignorance. There are generally three points:

  • find the subproblems in recursion first
  • find the condition to start recursion again
  • find the condition to end recursion again

in your example, the corresponding should be:

  • replace title with name
  • the current traversal object has a children attribute and is not empty
  • the current traversal object has no children or the children property is empty

then write a pseudo code according to this:

function recurse(node) {
    // 
    ...( title  name )
    
    // 
    if(node.children && node.children.length > 0) {
        // ...
        node.children.forEach(recurse)
    } else {
        // ...
        return
    }
}

then you will find that you only need to implement the part of the code that replaces title with name.


            function transferKey(arr){
                arr.forEach(obj => {
                    obj.name = obj.title
                    delete obj["title"]
                    if(obj.children instanceof Array){
                        transferKey(obj.children)
                    }
                })
                return arr
            }    
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9b1ca-1829.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9b1ca-1829.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?