130

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?

2
  • 6
    It looks like you should just use an array Commented Jan 19, 2012 at 12:14
  • 1
    instead of tempData.push( data ); write this tempData[index] = data. So you will not lose the order to. Commented Dec 16, 2021 at 18:27

10 Answers 10

162

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;
Sign up to request clarification or add additional context in comments.

6 Comments

+1 beat me to it. Don't forget to change the for...in loop, too.
@MattBall my bad! I am not really that adept at SO review and stuff! :)
Push is for array,Is there any way to add an array to an object?
What about associative array?
@KinnardHockenhull I'm sorry, I don't understand the question. Can you clarify what you're asking?
|
28

Objects does not support push property, but you can save it as well using the index as key,

var tempData = {};
for ( var index in data ) {
  if ( data[index].Status == "Valid" ) { 
    tempData[index] = data; 
  } 
 }
data = tempData;

I think this is easier if remove the object if its status is invalid, by doing.

for(var index in data){
  if(data[index].Status == "Invalid"){ 
    delete data[index]; 
  } 
}

And finally you don't need to create a var temp –

1 Comment

Add some explanation with answer for how this answer help OP in fixing current issue
6

You must make var tempData = new Array();

Push is an Array function.

11 Comments

Why new Array() and not []?
[] is an alternative (shortcut) to create new array. It can be made with [] and with new Array().
[] is the primary way of creating arrays, the other are alternatives and can even be overwritten.
See stackoverflow.com/questions/885156/… for a discussion of why new Array() is evil
w3schools.com/js/js_obj_array.asp new Array is regular array. Where [] defined as primary?
|
5

Javascript programming language supports functional programming paradigm so you can do easily with these codes.

var data = [
    {"Id": "1", "Status": "Valid"},
    {"Id": "2", "Status": "Invalid"}
];
var isValid = function(data){
    return data.Status === "Valid";
};
var valids = data.filter(isValid);

Comments

3

I hope this one might help you.

let data = [];
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };

let tempData = [];

tempData= data.filter((item)=>item.Status!='Invalid')

console.log(tempData)

Comments

2
    tempData.push( data[index] );

I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.

2 Comments

Please describe how to solve the problem in detail. Thanks.
This would be to correct the accepted answer from Matt Ball. As we are looping through data, we should only push data[index], not data entirely.
2

I assume that REALLY you get object from server and want to get object on output

Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])

var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response

data = { ...data,
  0: { "ID": "1", "Status": "Valid" },
  1: { "ID": "2", "Status": "Invalid" },
  2: { "ID": "3", "Status": "Valid" }
}

// solution 1: where output is sorted filtred array
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);
  
// solution2: where output is filtered object
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
  
// show
console.log('Object',data);
console.log('Array ',arr);

Comments

1

Mozilla actually shows you how to handle objects with push by chaining push to the call method:

"push is intentionally generic, and we can use that to our advantage. Array.prototype.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.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

const obj = {
  length: 0,

  addElem(elem) {
    // obj.length is automatically incremented
    // every time an element is added.
    [].push.call(this, elem);
  },
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2

Note that although obj is not an array, the method push successfully incremented obj's length property just like if we were dealing with an actual array."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Comments

0

You are getting that error because data.push only works with array, not object.

So here is what you can do:

var data = {};

data[0] = { "ID": "1"; "Status": "Valid" }
data[1] = { "ID": "2"; "Status": "Invalid" }

var tempData = {};
for ( var index in data ) {
if ( data[index].Status == "Valid" ) {
    tempData[index] = data[index];
}
}
data = tempData;

enter image description here

Comments

-2

Do :


var data = new Array();
var tempData = new Array();

2 Comments

Why new Array() and not []?
note the difference between new Array(); and new Array; You should be able to answer such questions instead of telling about alternatives..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.