Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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])
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

An example using 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);

about 4 years ago · Juan Pablo Isaza Report

0

Use this code

data.reduce((a,{qty, ...rest})=>a.concat(Array(qty).fill({...rest})),[]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!