Home > Software design >  ReactJs How to map field of an array into a new array?
ReactJs How to map field of an array into a new array?

Time:07-24

I'm new to javascript and react and working on my first mini project but I cannot figure out how to solve this.

In each "Order" model I have this array field called "orderItems" which holds an array of product models and within each product model there's a field called "shop". I want to get the "shop" value for all the products in orderItems and add it into a new array in "Order" model

Here is my schema:

{
  orderItems: [
    {
      name: 'abc',
      quantity: 1,
      shop: 'abc',
      image: '/images/cake.jpg',
      price: 50,
      _id: new ObjectId("62dbb03e90c4ca14ee3e06fd")
    },
    {
      name: 'def',
      quantity: 1,
      shop: 'def',
      image: '/images/cake.jpg',
      price: 50,
      _id: new ObjectId("62dbb03e90c4ca14ee3e06fd")
    }
  ],
  sellers: [],
  shippingAddress: {
    fullName: '123',
    address: '123',
    city: '123',
    postalCode: '123',
    country: '123'
  },
  paymentMethod: 'Paypal',
  itemsPrice: 50,
  shippingPrice: 10,
  totalPrice: 60,
  buyer: new ObjectId("62d6e48d8cd5cd2e62f6aeae"),
  _id: new ObjectId("62dbcf88cf1bc8fc7b85cc0b"),
  __v: 0
}

So I want to get 'abc', and 'def' from orderItems array and fill it in the sellers array. I can get the values but how do I fill it into the sellers array in the same model?

this is my api code

orderRouter.post(
  '/', isAuth, expressAsyncHandler(async(req, res) => {
    const newOrder = new Order({
      orderItems: req.body.orderItems.map((x) => ({ ...x, product: x._id })),
      shippingAddress: req.body.shippingAddress,
      paymentMethod: req.body.paymentMethod,
      itemsPrice: req.body.itemsPrice,
      shippingPrice: req.body.shippingPrice,
      totalPrice: req.body.totalPrice,
      buyer: req.user._id,
      sellers: [],
    });

    const order = await newOrder.save();
  })
);

I tried using a loop and then order.sellers.push(order.orderItems[i].shop) and then saving again but its not updating in my database & in local storage the _id field was pushed into the array instead of shop

CodePudding user response:

Step by step:

  1. Declare a separated const orderItems above const newOrder.
  2. Extract const sellers using a Set. You can also do it with an array or even an object, but Set will filter out duplicates automatically.
  3. The create the order, using the 2 consts above, and remember to turn the Set into an array.

Should look something like this:

const orderItems = req.body.orderItems.map((x) => ({ ...x, product: x._id }));

const sellers = [...new Set(orderItems.map(x => x.shop))];

const newOrder = new Order({
  orderItems,
  sellers: [...sellers],
  shippingAddress: req.body.shippingAddress,
  paymentMethod: req.body.paymentMethod,
  itemsPrice: req.body.itemsPrice,
  shippingPrice: req.body.shippingPrice,
  totalPrice: req.body.totalPrice,
  buyer: req.user._id,
});

And here's a working example:

const orderItems = [{
      name: 'P1',
      quantity: 1,
      shop: 'S1',
      image: '/images/p1.jpg',
      price: 50,
      _id: '62dbb03e90c4ca14ee3e06fa',
}, {
      name: 'P2',
      quantity: 1,
      shop: 'S2',
      image: '/images/p2.jpg',
      price: 50,
      _id: '62dbb03e90c4ca14ee3e06fb',
}, {
      name: 'P3',
      quantity: 1,
      shop: 'S1',
      image: '/images/p3.jpg',
      price: 50,
      _id: '62dbb03e90c4ca14ee3e06fc',
}];

const sellersSet = new Set(orderItems.map(x => x.shop));
const sellersArray = [...sellersSet];

// See here why the conversion to array is needed:
console.log({ sellersSet, sellersArray });

  • Related