Home > Enterprise >  Return multiple arrays with same name object
Return multiple arrays with same name object

Time:12-03

So I have a JSON File with multiple arrays "ID" that I want to extract.

[
  {
    "ID": 318,
    "Type": 0,
    "Value": 3,
     },
  {
    "ID": 580,
    "Type": 5,
    "Value": 8,
     },
  {
    "ID": 23,
    "Type": 3,
    "Value": 40,
     },
  {
    "ID": 13,
    "Type": 2,
    "Value": 58,
     },
  {
    "ID": 60,
    "Type": 54,
    "Value": 22,
     },
function getID(address){
  var url = 'https://data.com/api/v1/users/';
  var res = UrlFetchApp.fetch(url);
  var content = res.getContentText();
  var json = JSON.parse(content);
  var result = json[0]['ID'] ", " json[1]['ID'] ", " json[3]['ID'];
  return result;
}

I have this code that parses the arrays one by one but I don't know how to get all the "ID" arrays at once. Anyone that can help?

CodePudding user response:

To create the array:

var result = json.map(({ ID }) => ID);

to return the result as string:

return JSON.stringify(result);

And if you dont want the brackets:

return JSON.stringify(result).slice(1, -1);

CodePudding user response:

The OP might have a look into the documentation of ...

... and into ...

/*async */function getFetchedApiData(apiUrl) {
  return fetch(apiUrl)
    .then(response => response.json());
}

getFetchedApiData('https://jsonplaceholder.typicode.com/users')
  .then(data => {
    console.log({ data });
    return data;
  })
  .then(data =>
    data.map(item => item.id)
  )
  .then(idList => {
    console.log({ idList });
    return idList;
  })
  .then(idList => {
    console.log({ concatenatedIds: idList.join(', ') });
    // return idList;
  });
.as-console-wrapper { min-height: 100%!important; top: 0; }

... or with a slightly different syntax ...

async function getFetchedApiData(apiUrl) {
  return fetch(apiUrl)
    .then(response => response.json());
}

(async () => {

  const data = await getFetchedApiData('https://jsonplaceholder.typicode.com/users');
  const idList = data.map(({ id }) => id);
  const concatenatedIds = idList.join(', ');

  console.log({ data, idList, concatenatedIds });
  
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related