I'm trying to test something in javascript with an array and object here is what I'm trying to do:
CODE:
const data = [
{
name: "Order A",
orderItems: [
{
qty: [2, 2, 2],
products: [
{ name: "Product A" },
{ name: "Product B" },
{ name: "Product C" },
],
},
],
},
];
const dataName = data.map(({ name }) => {
return name;
});
const product = data.map(({ orderItems }) => {
return orderItems.map(({ qty, products }) => {
return products.map(({ name }) => {
return name + qty;
});
});
});
console.log(`This is ${dataName} with ${product}`);
I want it to return something like A2, B2, and C2 but it returns something like A2,2,2 B2,2,2 C2,2,2 I know I did something wrong. If you need anymore clarification please let me know.
BeerusDev
1,5193 gold badges15 silver badges34 bronze badges
asked Aug 6, 2021 at 13:26
Mohammad Khan
3631 gold badge4 silver badges22 bronze badges
2 Answers 2
You're concatenating the whole qty array. Pass the products array index and concatenate the corresponding qty instead.
const product = data.map(({ orderItems }) => {
return orderItems.map(({ qty, products }) => {
return products.map(({ name }, i) => {
return name + qty[i];
});
});
});
console.log(`This is ${dataName} with ${product}`);
Output
This is Order A with Product A2,Product B2,Product C2
answered Aug 6, 2021 at 13:35
Ravi K Thapliyal
51.9k9 gold badges80 silver badges90 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Try this? Don't forget you've got an index as the second param of array methods, and i think - you just need to use it to solve your problem :)
const ret = data.flatMap(({orderItems}) => orderItems).flatMap(({qty, products}) => {
return qty.flatMap((quantity, index) => ({quantity, name: products[index].name}))
});
ret.forEach(({name, quantity})=>console.log(name, quantity))
answered Aug 6, 2021 at 13:53
Artem Fedotov
4621 gold badge6 silver badges21 bronze badges
1 Comment
Mohammad Khan
Hello, thanks for answering it also worked. :))
lang-js
name + qtytheqtyvariable is an entire array.... Also, your data object isn't great, your products array would be easier to deal with if it contained this type of object{name: 'Product A', qty: 2}{name: 'Product A', qty: 2}the one you are saying but I need a way to make it something like that. If possible could you make something like that?