Javascript 基于属性删除JSON对象
我正在使用React,我得到了一个名为newtreeData的变量,它看起来像:Javascript 基于属性删除JSON对象,javascript,json,reactjs,Javascript,Json,Reactjs,我正在使用React,我得到了一个名为newtreeData的变量,它看起来像: var newTreeData = { name: submitted_title, resource_link: submitted_resource_link, details: submitted_details, uuid: submitted_uuid, website_image: submitted_website_img
var newTreeData = {
name: submitted_title,
resource_link: submitted_resource_link,
details: submitted_details,
uuid: submitted_uuid,
website_image: submitted_website_img,
children: [
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png",
children: [{...}, {}, ...]
},
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png"
}
]
};
行children:[{…},{}]只是表示newTreeData的子元素可以有子元素,而这些子元素可以有子元素
无论如何,我编写了一个名为findUUIDthenDelete的方法,它应该在伪代码中执行:ifobject.uuid==toFindUUID,然后删除对象,下面是findUUIDthenDelete的完整代码:
findUUIDthenDelete = (orig_data, to_delete_uuid) => {
var targetIsFound = false;
if (orig_data.uuid == to_delete_uuid) {
targetIsFound = true;
}
if (targetIsFound == false) {
if (orig_data.children === undefined) {
} else {
//if target not found, run recursion
orig_data.children.map(eachChildren =>
this.findUUIDthenDelete(eachChildren, to_delete_uuid)
);
}
} else {
console.log(orig_data, "this is the child ");
console.log(orig_data.parent, "is found, deleting its parent");
delete orig_data
}
};
正如您所看到的,这个方法分为两部分:首先,我找到了一个对象,该对象具有我们试图通过一些递归潜在地寻找的uuid,然后删除该对象。但是,现在我在局部变量严格模式下得到delete这个错误,因为我删除了原始数据。对该错误的解决方法有什么见解,或者有什么全新的解决方法?如果有一个明显的解决方案,我也真诚地道歉。我现在精神不好,想不出任何算法。这应该可以做到:
function findUUIDthenDelete(tree, uuid) {
if (!tree.children) return;
tree.children = tree.children.filter(c => c.uuid !== uuid);
tree.children.forEach(c => findUUIDthenDelete(c, uuid));
}
应该是不言自明的。
首先,如果当前节点没有子节点,请立即退出。
接下来,如果uuid使用过滤器匹配,则可能从子数组中删除一个子数组。
最后是递归。这应该可以做到:
function findUUIDthenDelete(tree, uuid) {
if (!tree.children) return;
tree.children = tree.children.filter(c => c.uuid !== uuid);
tree.children.forEach(c => findUUIDthenDelete(c, uuid));
}
应该是不言自明的。
首先,如果当前节点没有子节点,请立即退出。
接下来,如果uuid使用过滤器匹配,则可能从子数组中删除一个子数组。
最后是递归。好的,我承认这比我想象的要复杂,但是如果你能使用Immutable,下面的解决方案就行了。从本质上讲,它遍历对象并收集路径以查找具有uuid的对象,然后在完成此操作后将其删除 const testMap=Immutable.fromJS{ uuid:1, 儿童:[{ uuid:2, 儿童:[{ uuid:3, 儿童:[{ uuid:8 }] }, { uuid:4 }, { uuid:5 }, ] }, { uuid:7 }] }; 函数findPathcheckMap、uuid、pathMap、currentIndex{ 如果checkMap.has'uuid'&&checkMap.get'uuid'==uuid{ const updatePath=pathMap.get'path'.pushcurrentIndex; 返回新的Immutable.Map{ 发现:是的, 路径:路径映射。获取“路径”。pushcurrentIndex }; }否则{ 如果checkMap.has'children'&&checkMap.get'children.size>0{ 对于let i=0;i