javascriptarraysreactjstypescriptarrayobject

How to copy an object in the array to another array based on a specific value


I have an array

data = [
{code: 'A1', name: 'bag', qty: 3},
{code: 'A2', name: 'purse', qty: 2},
{code: 'A3', name: 'belt', qty: 1},
]

I want to omit qty & duplicate each item to another array based on each qty :

data = [
{code: 'A1', name: 'bag'},
{code: 'A1', name: 'bag'},
{code: 'A1', name: 'bag'},
{code: 'A2', name: 'purse'},
{code: 'A2', name: 'purse'},
{code: 'A3', name: 'belt'},
]

I've tried :

const [qtyList, setQtyList] = useState(
 new Array(renderData.length).fill(1)
);
const [selectedProduct, setSelectedProduct] = useState([])

const updatedQty = qtyList.map((q, index) => {
            if (index === k) return q = parseInt(val)
            else return q
        });
        setQtyList(updatedQty); //[3,2,1]

data.map((i, idx) => {
 let temp = []
 let existed = data.filter(x=>x.code==i.code).length
 for (let x=0; x<=qtyList[idx]; x++){
   temp.push(i)
 }
 setSelectedProduct((prev)=> [...prev, i])
}

Solution

  • Use the following code:

    var data = [
      { code: 'A1', name: 'bag', qty: 3 },
      { code: 'A2', name: 'purse', qty: 2 },
      { code: 'A3', name: 'belt', qty: 1 },
    ];
    
    var newArray = data.map(x => {
      return Array(x.qty).fill({ code: x.code, name: x.name })
    })
    
    console.log([].concat.apply([], newArray))