javascript - 根据属性删除 JSON 对象

标签 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,
        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 的 child 可以有 child ,而 child 可以有 child ...

无论如何,我写了一个方法名findUUIDthenDelete,它应该用伪代码来完成:if(object.uuid == toFindUUID) then delete object,下面是完整的代码找到UUID然后删除:

  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 orig_data,我收到“在局部变量严格模式中删除等等”错误。对该错误的任何解决方法或解决此问题的一些全新方法有任何见解?如果有明显的解决方案,我也深表歉意,我现在精神不振,无法想到任何算法。

最佳答案

应该这样做:

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 使用 filter() 匹配,可能会从 children 数组中删除一个子项。
最后,递归。

关于javascript - 根据属性删除 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54528313/

相关文章:

javascript - Node js请求体类型为[Object, Object]

java - 如果 Jackson Json 类字段扩展了 ArrayList,则无法序列化

jQuery append 表会自动在文本末尾添加结束标记。为什么?

reactjs - React webpack 应用程序 public/images 与 src/images

javascript - 找到一个返回值作为变量

javascript - 如何使用 blueimp 文件上传插件只上传一次文件?

javascript - 如何在 python 中加密/签名数据并使用 RSA 在 Reactjs 中解密?

html - 使组件添加新组件的问题

javascript - 如果 javascript 在 $(document).ready 函数中,它不允许我选择按钮

javascript - 如何使用 jQuery 解析 JSON