1

I have an object tree that contains the following values.

data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }

I am trying to check if the value of each heartbeat is 10 seconds less than the current time from epoch and if it is, delete the parent object.

Any help would be much appreciated!

s3SIM
  • 11
  • 1
  • 1
    I didn't understand the condition you wan to do, but I share you the code to replace with your condition, I'm using [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method. ```js Object.keys(data).forEach(key => { if(data[key].heartbeat === 10) { // your condition delete data[key] } }) `` – Dante Calderón Feb 12 '22 at 05:06
  • As @DanteCalderón mentioned you can use `Object.keys()` method for your problem statement. Link for the method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – Varun Arya Feb 12 '22 at 05:17

2 Answers2

0
data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }

for(let x in data) {
  // you have each object 
  console.log(data[x])
  // each heartbeat
  console.log(data[x]['heartbeat']);
  // each of joining time
  console.log(data[x]['joinTime']);
  // you can delete object after your condition satisfy  
  delete data[x];
};
-1

You can use the delete operator to completely remove the object that you want.

data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
}

for (let i in data) {
  if ({"less than 10 sec condtion will appear here"}) {
    delete data[i]
  }
}
Suraj Virkar
  • 511
  • 1
  • 4
  • 13
  • OP seems to be wanting to do this dynamically. They can't just hardcode the key like you're doing in your example (which seems to be the main problem they're having). If this was the answer, the question should be closed as a duplicate of instead of answered: [How do I remove a key from a JavaScript object?](https://stackoverflow.com/q/3455405), but there is a little more to it than just manually deleting a key. – Nick Parsons Feb 12 '22 at 05:10
  • Yes I have also written that "apply your conditions and use delete operator" @NickParsons – Suraj Virkar Feb 12 '22 at 05:16
  • I think it would improve your answer a lot if you added an example on how they can apply their conditions to use the `delete` operator in your code snippet, otherwise, this seems to only be half-answering the question... – Nick Parsons Feb 12 '22 at 05:23