Как достать подмассив из массива объектов?
Есть вот такой массив объектов, в котором лежит массив orders, нужно получить orders и вывести новый массив который будет содержать то что лежит в массиве orders.
const users = [
{
name: "Oleg Petko",
location: "Odesa",
orders: [
{
item_name: "tomato",
price: 10,
quantity: 23
},
{
item_name: "potato",
price: 5,
quantity: 6
},
]
},
{
name: "Vlad Diachenko",
location: "Odesa",
orders: [
{
item_name: "cigarets",
price: 65,
quantity: 10
},
{
item_name: "potato",
price: 5,
quantity: 1
},
]
},
{
name: "Sergey Diachenko",
location: "Oleshki",
orders: [
{
item_name: "cigarets",
price: 56,
quantity: 5
},
{
item_name: "tomato",
price: 25,
quantity: 11
},
]
},
{
name: "Roman Makarenko",
location: "Oleshki",
orders: [
{
item_name: "cigarets",
price: 76,
quantity: 2
},
{
item_name: "condoms",
price: 120,
quantity: 2
},
]
},
{
name: "Vlad Timoshenko",
location: "Oleshki",
orders: [
{
item_name: "tomato",
price: 34,
quantity: 2
},
{
item_name: "powder",
price: 56,
quantity: 4
},
]
}
]
let orderArray = [];
for (let i = 0; i < users.length; i++){
let currOrd = users[i];
if (currOrd == [orders]) {
currOrd.push(orderArray)
}
}
console.log(orderArray);
Ответы (1 шт):
Автор решения: Maxim
→ Ссылка
Если на выходе нужен массив с массивами orders, то можно сделать таким образом
const users = [
{
name: 'Oleg Petko',
location: 'Odesa',
orders: [
{
item_name: 'tomato',
price: 10,
quantity: 23,
},
{
item_name: 'potato',
price: 5,
quantity: 6,
},
],
},
{
name: 'Vlad Diachenko',
location: 'Odesa',
orders: [
{
item_name: 'cigarets',
price: 65,
quantity: 10,
},
{
item_name: 'potato',
price: 5,
quantity: 1,
},
],
},
];
const arrOfOrders = users.map(({ orders }) => orders);
console.log(arrOfOrders);
Выход будет такой
[
[
{ item_name: 'tomato', price: 10, quantity: 23 },
{ item_name: 'potato', price: 5, quantity: 6 }
],
[
{ item_name: 'cigarets', price: 65, quantity: 10 },
{ item_name: 'potato', price: 5, quantity: 1 }
]
]
UPD
Так как по сути изменять исходные значения на лету не нужно, то думаю логически вернее будет reduce()
Тогда можно сделать так:
const arrOfOrders = users.reduce((acc, item) => {
acc.push(item.orders);
return acc;
}, []);
На выходе получиться тоже самое:
[
[
{ item_name: 'tomato', price: 10, quantity: 23 },
{ item_name: 'potato', price: 5, quantity: 6 }
],
[
{ item_name: 'cigarets', price: 65, quantity: 10 },
{ item_name: 'potato', price: 5, quantity: 1 }
]
]
Или можно сделать так:
const arrOfOrders = users.reduce((acc, item) => {
return [...acc,...item.orders];
}, []);
Тогда на выходе мы получим массив объектов:
[
{ item_name: 'tomato', price: 10, quantity: 23 },
{ item_name: 'potato', price: 5, quantity: 6 },
{ item_name: 'cigarets', price: 65, quantity: 10 },
{ item_name: 'potato', price: 5, quantity: 1 }
]