简体   繁体   English

在数组中深度查找 object 并编辑然后放回原处

[英]Deep find object in array and edit then put back in place

const data = [{name: "item1", key: 1}, {name: "item2", key: 2, children: [{name: "item3", key: 3}]}]

each item can have children and objects in a children)每个项目都可以有孩子和孩子中的对象)

when will click to edit the function should give finded object by key or by given object:何时单击编辑 function 应该通过键或给定 object 找到 object:

findObj(3) //find by key findObj(3) //按键查找

//result {name: "item3", key: 3} //结果 {name: "item3", key: 3}

when will click to save after the editing the edited object should be saved in own place:编辑完后什么时候点击保存 编辑好的object应该保存在自己的地方:

saveEditing({name: "editedName", key: 3}) saveEditing({name: "editedName", key: 3})

//result [{name: "item1", key: 1}, {name: "item2", key: 2, children: [{name: "editedName", key: 3}]}] //结果 [{name: "item1", key: 1}, {name: "item2", key: 2, children: [{name: "editedName", key: 3}]}]

Find item by key按键查找项目

function findItemByKey(data, key){
  for(let node of data){
    if(node.key === key){
      return node;
    }
    if(node.children){
      let result = findItemByKey(node.children, key)
      if(result) {
        return result;
      }
    }
  }
  return undefined;
}

let result = findItemByKey(data, 3);
console.log(result); // { name: "item3", key: 3 }

Save item by key按键保存项目

function saveItemByKey(data, key, name){
  let result = findItemByKey(data, key);
  if(result){
    result.name = name;
  }
}

Just some rough solutions.只是一些粗略的解决方案。 You should be able to customize it from there.您应该可以从那里自定义它。

/** * @param {Number} key * @param {Array} array * @returns {Object} */ function findObj(key, array) { for (const item of array) { if (item.key === key) { return item } else if (item.children) { const foundChildren = findObj(key, item.children) if (foundChildren) return foundChildren } } return null } /** * @param {Object} obj * @param {Array} array * @returns Boolean */ function saveEditing(obj, array) { const foundObj = obj.key && findObj(obj.key, array) if (foundObj) { Object.assign(foundObj, {...obj}) return true } return false }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM