I have a fashion catalog, an inventory of items. Each designer has a lineup of items. Each item has a name and a price.
I have to write a function that will receive as a parameter an array. The function has to access all the items across each designer and return a matrix like:
[
[designer name, shoe name, price],
[designer name, shoe name, price],
...
]
But I'm stuck with this: ((this is my return))
[
'Brunello Cucinelli',
[ 'tasselled black low-top lace-up', 1000 ],
'Brunello Cucinelli',
[ 'tasselled green low-top lace-up', 1100 ],
'Brunello Cucinelli',
[ 'plain beige suede moccasin', 950 ],
'Brunello Cucinelli',
[ 'plain olive suede moccasin', 1050 ],
'Gucci',
[ 'red leather laced sneakers', 800 ],
'Gucci',
[ 'black leather laced sneakers', 900 ]
]
var currentInventory = [ //array with data
{
name: 'Brunello Cucinelli',
shoes: [
{ name: 'tasselled black low-top lace-up', price: 1000 },
{ name: 'tasselled green low-top lace-up', price: 1100 },
{ name: 'plain beige suede moccasin', price: 950 },
{ name: 'plain olive suede moccasin', price: 1050 }
]
},
{
name: 'Gucci',
shoes: [
{ name: 'red leather laced sneakers', price: 800 },
{ name: 'black leather laced sneakers', price: 900 }
]
}
];
function renderInventory(inventory) {
let matrix = []
let props = []
for(let i=0; i < inventory.length; i ){ //loop 1 inventory
matrix.push(inventory[i].name)
for(let n=0; n < inventory[i].shoes.length; n ){ //loop 2 shoes()
props.push(matrix[i])
props.push(Object.values(inventory[i].shoes[n]))
} //end loop 2
} //end loop 1
return props;
}
renderInventory(currentInventory)
Any help please?
CodePudding user response:
You can use a nested map()
call and then flatten the result (here using flatMap()
which combines the operations). This example also uses destructuring with aliases.
const currentInventory = [{ name: 'Brunello Cucinelli', shoes: [{ name: 'tasselled black low-top lace-up', price: 1000 }, { name: 'tasselled green low-top lace-up', price: 1100 }, { name: 'plain beige suede moccasin', price: 950 }, { name: 'plain olive suede moccasin', price: 1050 }] }, { name: 'Gucci', shoes: [{ name: 'red leather laced sneakers', price: 800 }, { name: 'black leather laced sneakers', price: 900 }] }];
const result = currentInventory
.flatMap(({ name: designer, shoes }) =>
shoes.map(({ name: shoe, price }) => [designer, shoe, price])
)
console.log(result)