Skip to content Skip to sidebar Skip to footer

Remove Parent Json Element Depending On Child Value

I have a JSON with lots of empty content: { 'items': [ { 'category': 'login', 'fields': [ { 'label': 'Name',

Solution 1:

Well, I found a way to iterate through the JSON object:

functionremove(jsondata) {
  for (let i in jsondata) {
    if (jsondata[i].value != undefined && jsondata[i].value == '') {
       delete jsondata[i];
    }
    elseif (typeof jsondata[i] === "object") remove(jsondata[i]);
  }
}

Not sure, if it's the most elegant way, but it works so far.

Solution 2:

use filter method,you could get a filtered array it returned Boolean. if value exist,it will be true

var list=JSON.parse(data)
list.items=list.items.map(val=>{
  val.fields=val.fields.filter(v=>v.value})
  return val
})

Solution 3:

We use object-scan for many data processing tasks. It's powerful once you wrap your head around it. Here is how you could answer your questions

// const objectScan = require('object-scan');constprune = (input) => objectScan(['**[*].value'], {
  rtn: 'count',
  filterFn: ({ gparent, gproperty, value }) => {
    if (value === '') {
      gparent.splice(gproperty, 1);
      returntrue;
    }
    returnfalse;
  }
})(input);

const obj = { items: [{ category: 'login', fields: [{ label: 'Name', value: '' }, { label: 'E-Mail', value: '' }, { label: 'Password', value: '123456' }, { label: 'Website', fields: [{ label: 'Name X', value: '' }, { label: 'Name Y', value: 'another one' }] }] }] };

console.log(prune(obj)); // return count of pruned entries// => 3console.log(obj);
// => { items: [ { category: 'login', fields: [ { label: 'Password', value: '123456' }, { label: 'Website', fields: [ { label: 'Name Y', value: 'another one' } ] } ] } ] }
.as-console-wrapper {max-height: 100%!important; top: 0}
<scriptsrc="https://bundle.run/object-scan@16.0.0"></script>

Disclaimer: I'm the author of object-scan

Post a Comment for "Remove Parent Json Element Depending On Child Value"