Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object push() function

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?

like image 712
Andrew Jackman Avatar asked Jan 19 '12 12:01

Andrew Jackman


People also ask

Can you use push on an object JavaScript?

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.

What is push () JS?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.

What is the opposite of push () in JavaScript?

The opposite of push() (as the question is titled) is pop() .


1 Answers

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; 
like image 125
Matt Ball Avatar answered Oct 22 '22 02:10

Matt Ball