118

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?

Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
Andrew Jackman
  • 13,275
  • 7
  • 34
  • 44

8 Answers8

149

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;
Matt Ball
  • 344,413
  • 96
  • 627
  • 693
23

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 –

csantana
  • 526
  • 7
  • 13
6

You must make var tempData = new Array();

Push is an Array function.

Alex Dn
  • 5,333
  • 7
  • 38
  • 77
  • 12
    Why `new Array()` and not `[]`? – Matt Ball Jan 19 '12 at 12:17
  • 3
    [] is an alternative (shortcut) to create new array. It can be made with [] and with new Array(). – Alex Dn Jan 19 '12 at 12:19
  • 6
    `[]` is the primary way of creating arrays, the other are alternatives and can even be overwritten. – Esailija Jan 19 '12 at 12:20
  • 7
    See http://stackoverflow.com/questions/885156/whats-wrong-with-var-x-new-array for a discussion of why `new Array()` is evil – Jonas Høgh Jan 19 '12 at 12:23
  • http://www.w3schools.com/js/js_obj_array.asp new Array is regular array. Where [] defined as primary? – Alex Dn Jan 19 '12 at 12:24
  • @Esailija I agree that not everything w3schools says is true and best practices. But I always knew that new Array() is a way to create arrays in JS and [] is a shortcut. Best practices is not a subject that OP asked about and it can be discussed for a long time. Anyway, [] is safer, new Array(100) is faster. – Alex Dn Jan 19 '12 at 12:32
  • @Esailija your test is not what I'm talking about...check this: http://jsperf.com/new-array-vs/2 – Alex Dn Jan 19 '12 at 12:54
  • @AlexDn those are not equivalent. `var a = new Array(100)` is the equivalent of `var a = []; a.length = 100;`. `new Array(100)` does not do anything but set the `length` to `100` – Esailija Jan 19 '12 at 12:56
  • @Esailija ok, I'm not choose the correct equivalent, but this is a modified test...still, new Array(100) is faster then []; [].length = 100; http://jsperf.com/new-array-vs/2 – Alex Dn Jan 19 '12 at 13:03
  • @AlexDn sure it is, and easier to write. But there are only very, very rare cases where you want `Array(x)` instead of `[]`. And `[]` is faster. – Esailija Jan 19 '12 at 13:13
  • @Esailija I agree, that's very rare case, but for OP question, the both versions will work. Best practices again, totally another discussion :) Why I wrote new Array and not [], just because it's the first thing that up in my mind...:) – Alex Dn Jan 19 '12 at 13:18
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);
regex
  • 101
  • 1
  • 9
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)
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

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);
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
-2

Do :


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

Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158