Hi all i have a small requirement where I will have the below array,
{items:[{upc:a,quantity:2},{upc:b,quantity:3}]}
I need to convert this to the below format
{products:[{barcode:a},{barcode:a},{barcode:b},{barcode:b},{barcode:b}]}
any ideas regarding this will be helpful
CodePudding user response:
Yes, javascript have native methods that allow to do it.
const source = {items:[{upc:'a',quantity:2},{upc:'b',quantity:3}]}
const res = source.items.map(item => new Array(item.quantity).fill({barcode: item.upc})).flat()
console.log({products: res});
PS: The output looks a bit weird, because several fields contains reference to same object - the console.log is telling it to you so it does not have to repeat output for each object.
But the object itself contains the values you need. If you need to have separate objects (i.e. if you want to update just one of them), then you can do it as following:
const source = {items:[{upc:'a',quantity:2},{upc:'b',quantity:3}]}
const res = source.items.map(item => new Array(item.quantity).fill(0).map(x => ({barcode: item.upc}))).flat()
console.log({products: res});