Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS/Apps Script: How do I map nested keys?

In the following Google Apps Script code, I want to write three keys to the sheet key_1,key_3.subkey and key_4[1].key. How do fix my code to show the subkey and second element of key_4 as well?

function main() {

  const data = [{"key_1":10,"key_2":20,"key_3":{"subkey":30},"key_4":[{"key":41},{"key":42}]},{"key_1":40,"key_2":50,"key_3":{"subkey":60},"key_4":[{"key":43},{"key":44}]}];
  const keys = ["key_1","key_3.subkey","key_4[1].key"];


  print(data, keys);

}

function print(data, keys) {

  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("Test");
  sheet.clear();

  for (let i=0; i<data.length; i++) {
    arr = Array(keys.map(k => data[i][k]));
    sheet.getRange(i+1,1,1,2).setValues(arr);
  }
}

Solution

function main() {
  const data = [{"key_1":10,"key_2":20,"key_3":{"subkey":30},"key_4":[{"key":41},{"key":42}]},{"key_1":40,"key_2":50,"key_3":{"subkey":60},"key_4":[{"key":43},{"key":44}]}];
  const keys = ["key_1","key_3.subkey","key_4.1.key"];
  print(data, keys);
}

function print(data, keys) {
  for (let i=0; i < data.length; i++) {
    let arr = keys.map(k => k.split('.').reduce((a, b) => a[b], data[i]));
    Logger.log(arr);
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use a format where all subkeys are separated by .. Then, you can split the string on . and use Array#reduce to traverse the nested data structure.

function main() {
  const data = [{"key_1":10,"key_2":20,"key_3":{"subkey":30},"key_4":["","4a"]},{"key_1":40,"key_2":50,"key_3":{"subkey":60},"key_4":["","4b"]}];
  const keys = ["key_1","key_3.subkey","key_4.1"];
  print(data, keys);
}
function print(data, keys) {
  for (let i=0; i < data.length; i++) {
    let arr = keys.map(k => k.split('.').reduce((a, b) => a[b], data[i]));
    console.log(arr);
  }
}
main();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading