0

Here is my function:

function RemoveOutputKeys(array){
  var temp = array;
  for(var object in temp){
    delete temp[object]['statusCode']
    delete temp[object]['statusResponse']
  } 
  console.log(array)
  if(temp == array)
    console.log("how is this possible?!?!!?!?!")
  return temp
}

and here is the input I am providing,

array = [{'statusCode':400},{'statusCode':200}]

It makes sense for temp to get updated but I don't want the array to get updated. How can i fix this issue?

Thanks

J. Doe
  • 37
  • 2
  • 8
  • 3
    `var temp = array;` doesn't make a new array. You're still working on `array`. – user2357112 Nov 01 '16 at 22:46
  • 1
    Don't use `for(... in...)` to iterate arrays – MinusFour Nov 01 '16 at 22:46
  • Also, `if(temp == array)` is an object identity comparison, not a value comparison. – user2357112 Nov 01 '16 at 22:46
  • Your `temp` variable just **points** to your array, it is done through a reference. – Robo Robok Nov 01 '16 at 22:47
  • I see! Never knew that – J. Doe Nov 01 '16 at 22:47
  • Why is for(...in...) bad for iterating? – J. Doe Nov 01 '16 at 22:48
  • Ill gogle that above comment^ Dw about it – J. Doe Nov 01 '16 at 22:48
  • @J.Doe basically, `for...in` is bad, because it iterates over _object properties_, so it can behave oddly with arrays. In older browsers, it also iterated over stuff like `.length` and `.indexOf()`, for example. You can see more [here](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea). You can use the newer [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) or a normal `for` loop to do it. – VLAZ Nov 01 '16 at 23:02

2 Answers2

1

Use Array.prototype.filter() instead of for in

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

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

function RemoveOutputKeys(array) {
  return array.filter(function(myArray) {
      if (!myArray['statusCode'] && !myArray['statusResponse']) {
          return myArray;
      }
  });
}

var originalArray = [{'statusCode':400}, {'statusCode':200}, {'test': 'test'}];

var tempArray = RemoveOutputKeys(originalArray);

console.log(originalArray, tempArray);

https://jsfiddle.net/3kbypvcs/2/

Marco Magrini
  • 749
  • 1
  • 9
  • 19
0

If you want create new array instead of alias/reference use:

var newArray = oldArray.slice();
user3464829
  • 69
  • 1
  • 9