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

Time:01-13

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

CodePudding user response:

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

CodePudding user response:

my approach using reduce

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

let a = data.reduce((acc,curr)=>{
    const {code,name,qty} = curr;
  for (let i = 0; i < qty; i  ) {
    acc.push({code,name});
    }
  
  return acc;
},[])

console.log(a)

CodePudding user response:

data.map(item => Array(item.qty).fill({ code: item.code, name: item.name })).flat();

CodePudding user response:

There is probably a more elegant solution to this problem, but this was my quick fix:

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

CodePudding user response:

Use this code

data.reduce((a,{qty, ...rest})=>a.concat(Array(qty).fill({...rest})),[]);
  •  Tags:  
  • Related