Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
remove a attribute recursively in a object in javascript

here is simple data, i want to recursively remove the children attribute if the children attribute represents a empty array.

[{"name":"code","created":"2022-03-27T05:42:28.977Z","children":[],"path":"623ff9881a6e94547deaebed"}]

my code is as shown

  function removeMeta(obj) {
    let keys = Object.keys(obj);
    for(let key in keys) {
      console.log('.......',key,obj[key]);
      if(typeof(obj[key]) == 'object'){
        removeMeta(obj[key]);
      }else if( key == 'children' && obj[key] ==[]){
        delete obj[key];
      }
    }
  }

but it doesn't seem to work, any idea

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

These are the issues:

  • The typeof the children property will be 'object', so your code will never perform the delete.

    Remove the else from else if, so that that if is always executed.

  • obj[key] ==[] will always be false, as it compares with a newly created array -- by reference. Instead check the length:

    obj[key].length == 0
    
  • The for loop should be a for..of loop, not a for..in loop

Corrected:

function removeMeta(obj) {
  let keys = Object.keys(obj);
  for(let key of keys) {
    if(typeof(obj[key]) == 'object'){
      removeMeta(obj[key]);
    }
    if( key == 'children' && obj[key].length == 0){
      delete obj[key];
    }
  }
}

let arr = [{"name":"code","created":"2022-03-27T05:42:28.977Z","children":[],"path":"623ff9881a6e94547deaebed"}];
removeMeta(arr);
console.log(arr);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!