Home > Software engineering >  How to split the object into two according to it's own data in array of object in javascript
How to split the object into two according to it's own data in array of object in javascript

Time:03-24

I was given a case to split the array of object according to it's own quantity of the object data

Case 1:

const product = [{
    product_sku: 'p1',
    product_qty: 2,
  },
  {
    product_sku: 'p2',
    product_qty: 1,
  }, ,
  {
    product_sku: 'p3',
    product_qty: 2,
  },
]

Expected Outcome:

const product = [{
    product_sku: 'p1',
    product_qty: 2,
  },
  {
    product_sku: 'p1',
    product_qty: 2,
  },
  {
    product_sku: 'p2',
    product_qty: 1,
  }, ,
  {
    product_sku: 'p3',
    product_qty: 2,
  },
  {
    product_sku: 'p3',
    product_qty: 2,
  },
]

The outcome of the result will depend on the iteration of its own quantity of product

CodePudding user response:

You could Array#flatMap and create a nested array with the wanted amount of copies of the object.

const
    products = [{ product_sku: 'p1', product_qty: 2 }, { product_sku: 'p2', product_qty: 1 }, { product_sku: 'p3', product_qty: 2 }],
    result = products.flatMap(product =>     // map a new flat array
        Array.from(                          // create a new array
            { length: product.product_qty }, // with a defined length and
            () => ({ ... product })          // map new object
        )
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

oen way can be to have an intermediate result array to stored duplicate data

variable in js are reference to duplicate your object in new array you can use structuredClone({yourObject})

const product = [{
    product_sku: 'p1',
    product_qty: 2,
  },
  {
    product_sku: 'p2',
    product_qty: 1,
  }, ,
  {
    product_sku: 'p3',
    product_qty: 2,
  },
];

var result = [];
product.forEach(one => {
  Array(one.product_qty).fill(0).forEach(fake => {
    result.push(structuredClone(one));
  });
});

console.log(result);

CodePudding user response:

Try this Code.

    const product = [
  {
    product_sku: 'p1',
    product_qty: 2,
  },
  {
    product_sku: 'p2',
    product_qty: 1,
  },
  ,
  {
    product_sku: 'p3',
    product_qty: 2,
  }
];

let outProduct = [];

product.forEach(el => {
  for (let index = 0; index < el["product_qty"]; index  ) {
    outProduct.push(
      {
        product_sku: el["product_sku"],
        product_qty: index   1
      }
    );
  }
})

console.log(outProduct);

CodePudding user response:

Try this :

const product = [{
  product_sku: 'p1',
  product_qty: 2,
}, {
  product_sku: 'p2',
  product_qty: 1,
}, {
  product_sku: 'p3',
  product_qty: 2,
}];

const res = [];

product.forEach((obj) => {
  for (let i = 0; i < obj.product_qty; i  ) {
    res.push(obj)
  }
});

console.log(res);

  • Related