0

lets say that you make a call to an API and get back an array of values like this

{
 orders: [
     {
       id: '159151',
       owner: 'steve',
       created_at: '1662518452935217224',
     }
   ]
 }

to pull the id value I would normally write

const id = orders.orders[0].id

. sometimes however I get multiple back at the same time. it ranges from 1 - unknown and need to pull and input all the ids .

{
  orders: [
    {
      id: '159151',
      owner: 'steve',
      created_at: '1662518452935217224',
    },
    {
      id: '159152',
      owner: 'john',
      created_at: '1662518628829631781',
    },
    {
      id: '159164',
      owner: 'bob',
      created_at: '1662519501403450193',
    }
  ]
}

what can you do if you need to pull multiple id values at the same time but your unsure of the amount of id values that will be returned when you make the call to the API?

Stephen
  • 11
  • 3
  • `ids = orders.orders.map(order => order.id)` (assuming `idx` is a typo). – Dave Newton Sep 07 '22 at 03:07
  • 1
    Does this answer your question? [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – Strelok Sep 07 '22 at 03:08

3 Answers3

0

Assuming all the id keys in your example were the same (rather than idx). How about mapping them to an array?

const response = {
  orders: [
    {
      id: '159151',
      owner: 'steve',
      created_at: '1662518452935217224',
    },
    {
      id: '159152',
      owner: 'john',
      created_at: '1662518628829631781',
    },
    {
      id: '159164',
      owner: 'bob',
      created_at: '1662519501403450193',
    }
  ]
}

const ids = response.orders.map(order => order.id);
const count = ids.length

console.log(ids, count)
Steve
  • 4,372
  • 26
  • 37
  • that was able to asses how many there where but the values returned undefined – Stephen Sep 07 '22 at 03:14
  • @Stephen It doesn't; you can run it. We can't see your *actual* data; this answer names the object containing `orders` something sensible. – Dave Newton Sep 07 '22 at 03:17
0

Use Array.prototype.map:

const data = { orders: [{ id: 12345 }, { id: 56789 }, { id: 192837 }] }
const ids = data.orders.map(o => o.id)
console.log(ids)
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
JSmart523
  • 2,069
  • 1
  • 7
  • 17
0

You can simply achieve that with a single line of code with the help of Array.map() method.

Live Demo :

const obj = {
  orders: [
    {
      id: '159151',
      owner: 'steve',
      created_at: '1662518452935217224',
    },
    {
      id: '159152',
      owner: 'john',
      created_at: '1662518628829631781',
    },
    {
      id: '159164',
      owner: 'bob',
      created_at: '1662519501403450193',
    }
  ]
};

const idsArr = obj.orders.map(({ id }) => id);

console.log(idsArr);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123