美文网首页
js 递归,根据key或id,替换嵌套数组对象里面的对象

js 递归,根据key或id,替换嵌套数组对象里面的对象

作者: _一九九一_ | 来源:发表于2019-06-17 19:35 被阅读0次

需求:

将key为123的对象,替换成newObj,他们的key相同

知识点

for循环--更改原数组

let obj = {
  key:'111'
  title: 'title',
  children:[
     {
        key:'123'
        title: '旧title',
     }
  ]
}
let newObj = {
   key:'123'
   title: '新title'
}



let editTreeData = (treeData,newTreeNode) => { 
    for (let i = 0, len = treeData.length; i < len; i++) { 
      if(treeData[i].children){
          this.editTreeData(treeData[i].children,newTreeNode)
        }   
      if (treeData[i].key === newTreeNode.key) {
        treeData[i] = newTreeNode;
      }
    }
    return treeData 
}



editTreeData(obj,newObj)

// 输出
let obj = {
  key:'111'
  title: 'title',
  children:[
     {
        key:'123'
        title: '新title',
     }
  ]
}

相关文章

网友评论

      本文标题:js 递归,根据key或id,替换嵌套数组对象里面的对象

      本文链接:https://www.haomeiwen.com/subject/ubvzfctx.html