0

I have array what looks like this:

var arr = [{name: 'Test', id: 1}, {name: 'Test', id: 2}, {name: 'Test', id: 3}];

When I looping through this array I want to prepare new array:

var new_arr = [];
for (var key in arr) {
    if (arr[key].name == 'Test') {
        new_arr.push(arr[key]);
    }
}

But when I Logger.log(new_arr) it looks:

[{name: 'Test': id: 3}]

So the questions is: What is wrong with this code!? When I log each item all fine, but it looks like it push only last element. Thanks!

P.S. I tested this code on local machine and all works fine!

Kriggs
  • 3,731
  • 1
  • 15
  • 23
nowiko
  • 2,507
  • 6
  • 38
  • 82
  • Are you sure you're loggin at the right time? Here it's working just fine. – Kriggs Jul 31 '15 at 11:18
  • 1
    [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) (unlikely to be the problem though) – Bergi Jul 31 '15 at 12:01

5 Answers5

1

It works perfectly in the Google Script editor too...

code :

function test(){
  var arr = [{name: 'Test', id: 1}, {name: 'Test', id: 2}, {name: 'Test', id: 3}];      
  var new_arr = [];
  for (var key in arr) {
    if (arr[key].name == 'Test') {
      new_arr.push(arr[key]);
    }
  }
  Logger.log(new_arr);
}

result :

enter image description here

Serge insas
  • 45,904
  • 7
  • 105
  • 131
0

If you are using the Logger.log() method of the Google Apps Script, you are passing wrong parameters, log() spects an string..

https://developers.google.com/apps-script/reference/base/logger#log

Try to do this.. and check again:

Logger.log(JSON.stringify(new_arr));
0

When I do a

console.debug(new_arr);

I get

[Object { name="Test",  id=1}, Object { name="Test",  id=2}, Object { name="Test",  id=3}]

So your code ist fine. Just the logger seems to be funky.

luba
  • 104
  • 4
0

I don't see why it wouldn't work. As long as you are using Logger.log in the correct place. I did the following and placed Logger.log after the for loop:

function test() {
  var arr = [{
    name: 'Test',
    id: 1
  }, {
    name: 'Test',
    id: 2
  }, {
    name: 'Test',
    id: 3
  }];

  var new_arr = [];

  for (var key in arr) {
    if (arr[key].name == 'Test') {
      new_arr.push(arr[key]);
    }
  }

  Logger.log(new_arr);

}

When I look at the log, the result is what you were expecting to see:

[15-07-31 13:40:31:846 EDT] [{name=Test, id=1.0}, {name=Test, id=2.0}, {name=Test, id=3.0}]

Let me know if I misunderstood your question.

Laurent Meyer
  • 2,766
  • 3
  • 33
  • 57
Scott
  • 1
-1

The problem is that you run:

for(var key in arr)

Which is meant for looping over Objects properties.

Use the following for looping over arrays

for (i = 0; i < arr.length; i++) { 
    if (arr[i].name == 'Test') {
        new_arr.push(arr[i]);
    }    
}

Or you could use the Array.prototype.filter

var new_arr = arr.filter(function(item){
    return item.name === 'Test'
})

Or a while loop, whatever you prefer

Endless
  • 34,080
  • 13
  • 108
  • 131