Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - How to set data to object in JS/TS?

At response to my api I must return a parsed data, which i set in belowed way to my UserModelResponse which i return in API:

        const userModelResponse = new UserModelResponse();

        userModelResponse.description = responseData.description;
        userModelResponse.full_name = responseData.full_name;
        userModelResponse.sex = responseData.sex ;


        const orders = [];
        responseOrderData.forEach((e) => {
            const orderModel = new OrderModel();

            orderModel.price = e.price;
            orderModel.weight = e.weight;
            orderModel.time = e.time;

            orders.push(orderModel );
        })
        userModelResponse.orders = orders ;

is there a better and faster way to set data from db(responseData and responseOrderData) to my UserModelResponse? thanks for any help


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it a little more cleanly with Array.map, but the speed of it will be negligable:

userModelResponse.orders = responseOrderData.map((e) => {
  const orderModel = new OrderModel();
  orderModel.price = e.price;
  orderModel.weight = e.weight;
  orderModel.time = e.time;
  return orderModel;
});

If the OrderModel constructor accepts something like an object of default values, then you could do something like:

userModelResponse.orders = responseOrderData.map(e => new OrderModel(e));

Edit: Updated the new OrderModel part following @Bergi's comment.

The constructor of OrderModel would need to look something like:

class OrderModel {
  constructor(order) {
    this.price = order.price;
    this.weight = order.weight;
    this.time = order.time;
  }

  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...