简体   繁体   English

通过其键值从嵌套的 JSON 中查找并删除 object

[英]find and delete object from nested JSON by its key value

I want to delete an object inside a nested JSON.我想在嵌套的 JSON 中删除 object。 As in example below, my aim is to delete the maths from the object.如下例所示,我的目标是从 object 中删除数学。 But I have to search the "mat" key and delete it.但我必须搜索“mat”键并将其删除。 in my actual case, there are 10s of objects in subjects property.在我的实际情况中,subjects 属性中有 10 个对象。

 const obj = {
       "id":"1234",
       "name":"John Doe",
       "level":"elementary",
       "subjects":[
          {
             "key":"mat",
             "name":"maths",
             "teacher":"Mr Smith",
          },
          {
             "key":"eng",
             "name":"english",
             "teacher":"Mrs Smith",
          }
       ],
       "homeroom_teacher":"Mrs Brown"
    }

after the deletion I want to have:删除后我想要:

 const obj = {
       "id":"1234",
       "name":"John Doe",
       "level":"elementary",
       "subjects":[
          {
             "key":"eng",
             "name":"english",
             "teacher":"Mrs Smith",
          }
       ],
       "homeroom_teacher":"Mrs Brown"
    }

I would filter我会过滤

 const obj = { "id":"1234", "name":"John Doe", "level":"elementary", "subjects":[ { "key":"mat", "name":"maths", "teacher":"Mr Smith", }, { "key":"eng", "name":"english", "teacher":"Mrs Smith", } ], "homeroom_teacher":"Mrs Brown" }; const keep = ["eng"]; // assuming more could be present obj.subjects = obj.subjects.filter(({key}) => keep.includes(key)) console.log(obj)

Here is an iterative solution using object-scan .这是使用object-scan的迭代解决方案。 Vanilla js might be preferable, depending on your use case. Vanilla js 可能更可取,具体取决于您的用例。 This solution aims to be flexible该解决方案旨在灵活

 // const objectScan = require('object-scan'); const myObj = { id: '1234', name: 'John Doe', level: 'elementary', subjects: [{ key: 'mat', name: 'maths', teacher: 'Mr Smith' }, { key: 'eng', name: 'english', teacher: 'Mrs Smith' }], homeroom_teacher: 'Mrs Brown' }; const remove = (obj, k) => objectScan(['subjects[*].key'], { abort: true, rtn: 'bool', filterFn: ({ value, gparent, gproperty }) => { if (value === k) { gparent.splice(gproperty, 1); return true; } return false; } })(obj); console.log(remove(myObj, 'mat')); // => true console.log(myObj); /* => { id: '1234', name: 'John Doe', level: 'elementary', subjects: [ { key: 'eng', name: 'english', teacher: 'Mrs Smith' } ], homeroom_teacher: 'Mrs Brown' } */
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@15.0.0"></script>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

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

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