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?
CodePudding user response:
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)
CodePudding user response:
Use Array.prototype.map:
const data = { orders: [{ id: 12345 }, { id: 56789 }, { id: 192837 }] }
const ids = data.orders.map(o => o.id)
console.log(ids)
CodePudding user response:
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);