如何根据特定值将数组中的对象复制到另一个数组

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

我有一个数组

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

我想省略 qty 并根据每个 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'},
]

我试过了:

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])
}

使用以下代码:

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))

使用此代码

data.reduce((a,{qty, ...rest})=>a.concat(Array(qty).fill({...rest})),[]);
data.map(item => Array(item.qty).fill({ code: item.code, name: item.name })).flat();

这个问题可能有更优雅的解决方案,但这是我的快速解决方案:

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

let dupArr = []

data.map((i) =>{
   for(let j = 0;j<= i['qty']-1; j++){
       dupArr.push(i);
   }
});

dupArr.map((idx)=>{
    delete idx['qty'];
})

console.log(dupArr);

使用 flatMap

的示例

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

const o = data.flatMap(({ code, name, qty }) =>
    Array(qty).fill({ code, name })
);

console.log(o);