Benarab Badi
Benarab Badi

Reputation: 51

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:

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

the result of execution:

undefined
undefined
undefined

any help!

Upvotes: 1

Views: 5682

Answers (3)

ysfiqbl
ysfiqbl

Reputation: 396

In your code XXX is the key. You need to do graph[XXX] to access the actual object. So instead of XXX.a you should do graph[XXX].a. But this only accounts for objects in graph that have an the key a. You also need to account for key a in graph. Please see the code below. Its a rudimentary example.

If you have one level of nesting then you can use then you can use the code below.

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

console.log(mygraph);

function deletePropAndValuesOf(key, graph) {

  for (const k of Object.keys(graph)) {
    if (k === key) {
      delete graph[key];
    } else {
      if (key in graph[k]) {
        delete graph[k][key]
      }
    }
  }
}

deletePropAndValuesOf("a", graph);

console.log(mygraph);

You can copy the code to a .js file and run it using node. e.g. enter image description here

Upvotes: 1

Ahmed Warsama
Ahmed Warsama

Reputation: 1

Ive used object destructuring to remove the first array with an a, but could not figure out how to do all the a's's but the code below might help?

const MyGraph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 }};
const {a, ...newMyGraph} = MyGraph;
// output
console.log(newMyGraph)

returns

b: {
   a: 5,
   c: 7,
   d: 8
},
c: {
   a: 2,
   b: 7,
   d: 4,
   e: 8
}
}

Upvotes: -1

Peterrabbit
Peterrabbit

Reputation: 2247

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)

Upvotes: 5

Related Questions