Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apps script: map not returning expected value to array

I have an array of objects that looks like:

var objArray = [
  {
    " #": "4596",
    " E": "Yes",
    " Date": "06/12/20",
    " County": "Los Angeles County",
    " State": "California",
    " Acres": "2.49",
    " Eager": "Low",
  },
  {
    " #": "4588",
    " E": "Yes",
    " Date": "06/11/20",
    " County": "Towns County",
    " State": "Georgia",
    " Acres": "3.00",
    " Eager": "High",
  },
  ....
];

I'm trying to put together an array of the indexes ('#');

So far I have:

let indexes = objArray.forEach(function (rowObj) {
  Object.keys(rowObj).map(function (key) {
    if (key.includes("#")) {
      var v = rowObj[key];
      Logger.log(v); // abc
      return v;
    }
  });
});

Logger.log(indexes); // abc

output:

[20-06-13 20:43:33:320 EDT] 4547
[20-06-13 20:43:33:324 EDT] 4546
[20-06-13 20:43:33:329 EDT] 4545
[20-06-13 20:43:33:450 EDT] 4543
[20-06-13 20:43:33:453 EDT] 4542
[20-06-13 20:43:33:456 EDT] 4540
[20-06-13 20:43:33:459 EDT] 4538

This is producing:

[20-06-13 20:43:33:462 EDT] null

What am I doing wrong?

like image 630
user1592380 Avatar asked Jul 04 '26 07:07

user1592380


1 Answers

As a supplementary answer:

You can do this even simpler and faster.

const values = [
  { " #": "4596", " E": "Yes"},
  { " #": "4597", " E": "No"},
  { " #": "4598", " E": "Maybe"},
]

const indices = values.map(({ " #" : id }) => id);

console.log(indices);

Please, note that callback to map() method should be deterministic to acheive a consistent result.

Actual problem

Check the documentation on forEach() method - it is intended for producing side-effects and therefore returns void (literally no value), hence the last Logger.log(indexes); issue.

Useful links

  1. map() method reference
  2. Arrow functions guide
  3. forEach() method reference
like image 196
Oleg Valter is with Ukraine Avatar answered Jul 05 '26 22:07

Oleg Valter is with Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!