简体   繁体   中英

find and delete object from nested JSON by its key value

I want to delete an object inside a nested JSON. As in example below, my aim is to delete the maths from the object. But I have to search the "mat" key and delete it. in my actual case, there are 10s of objects in subjects property.

 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 . Vanilla js might be preferable, depending on your use case. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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