Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete property and its values in all the object

I’m a beginner in javaScript, I have this object MyGraph:

const MyGraph = {
    a: { b: 5, c: 2 },
    b: { a: 5, c: 7, d: 8 },
    c: { a: 2, b: 7, d: 4, e: 8 },
};

I want to delete property "a" and its values in other properties as well to get this result:

const MyGraph = {
    b: { c: 7, d: 8 },
    c: { b: 7, d: 4, e: 8 },
};

I tried like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for(let XXX of Object.keys(MyGraph)){
    console.log(XXX.a);
    delete XXX.a;
}

the result of execution:

undefined
undefined
undefined

any help!

>Solution :

You could use a recursive algorithm :

function del_entries(key, obj) {
  if (obj.hasOwnProperty(key)) {
    delete obj[key];
  }

  // Or with Object.hasOwn, not fully supported by old browsers but more up to date
 /*
 if (Object.hasOwn(obj, key)) {
     delete obj[key]
 }
 */
  
  Object.values(obj).forEach(o=> del_entries(key, o))
}


const MyGraph = {
    a: { b: 5, c: 2 },
    b: { a: 5, c: 7, d: 8 },
    c: { a: 2, b: 7, d: 4, e: 8 },
};

del_entries("a", MyGraph);

console.log(MyGraph)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading