Reputation: 113
I have a JSON array which looks like this:
{
"Times": [
{
"TimeStamp": "1588516643",
"PremiumTime": "1",
"ID": "473873947895897",
"GuildID": "27823978489723789"
},
{
"TimeStamp": "1588516643",
"PremiumTime": "1",
"ID": "473873947895897",
"GuildID": "27823978489723789"
}
]
}
Is There an easy way to remove all elements that meet a condition, I want to remove it if the TimeStamp in that element is less than or equal to a variable.
I've tried looping through the array but when i remove something from it i have to start the loop again because the object changed and doing that gives me errors.
Upvotes: 0
Views: 2223
Reputation: 7546
An alternative you should be aware of is to loop backwards. The problem you are seeing is likely because when you remove an item, the index of every later item changes. The length of the array is decremented too.
But notice that earlier items in the array are not affected. So start at the far end of the array and work your way back towards the start.
And we don't care that the length changes because we only check the length once at the start of the loop, not every iteration.
let obj = {
"Times": [{
"TimeStamp": "1588516642",
},
{
"TimeStamp": "1588516643",
},
{
"TimeStamp": "1588516644",
}]
}
for (let i = obj.Times.length - 1; i > -1; i--) {
if (obj.Times[i].TimeStamp <= 1588516643) {
obj.Times.splice(i, 1);
}
}
console.log(obj.Times);
Upvotes: 3
Reputation: 1767
Try using a filter in JS
Assuming x is your JSON data and req_value is your required value of timestamp.
var req_value = '1588516641';
var y = x.Times.filter(function(item, index){
return item.TimeStamp <= req_value;
})
console.log(y)
Upvotes: 0
Reputation: 117
This would do,
const obj = {
"Times": [{
"TimeStamp": "1588516642",
"PremiumTime": "1",
"ID": "473873947895897",
"GuildID": "27823978489723789"
},
{
"TimeStamp": "1588516643",
"PremiumTime": "1",
"ID": "473873947895897",
"GuildID": "27823978489723789"
}
]
}
const filterTimestamp = 1588516642;
const result = obj.Times.filter(element => element.TimeStamp > filterTimestamp);
console.log(result)
Upvotes: 0