I have a javascript object (I actually get the data through an ajax request):
var data = {};
I have added some stuff into it:
data[0] = { "ID": "1"; "Status": "Valid" } data[1] = { "ID": "2"; "Status": "Invalid" }
Now I want to remove all objects with an invalid status (but keep everything the ordering same):
var tempData = {}; for ( var index in data ) { if ( data[index].Status == "Valid" ) { tempData.push( data ); } } data = tempData;
In my mind, all of this should work, but I am getting an error that tempData.push
is not a function. I understand why it isn't the same as an array, but what could I do otherwise?
push can work on an object just fine, as this example shows. Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.
JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.
The opposite of push() (as the question is titled) is pop() .
push()
is for arrays, not objects, so use the right data structure.
var data = []; // ... data[0] = { "ID": "1", "Status": "Valid" }; data[1] = { "ID": "2", "Status": "Invalid" }; // ... var tempData = []; for ( var index=0; index<data.length; index++ ) { if ( data[index].Status == "Valid" ) { tempData.push( data ); } } data = tempData;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With