首页 > 解决方案 > 带有方法的属性的 Javascript 对象文字

问题描述

const products = [
        {
            id: 5,
            productName: "Logitech Mouse",
            unitprice: 35
        },
        {
            id: 6,
            productName: "Logitech Keyboard",
            unitprice: 40
        }
    ];

    const carts = [
        {
            id: 101,
            userId: 3,
            productId: 5,
            quantity: 2,
            total: function () {
                 return this.unitprice * this.quantity             
            }
        }        
    ];

    let joined = carts.map(item => {
        console.log(item.total);
        let { id, ...rest } = products.find(p => p.id === item.productId);
        debugger
        return {
            ...rest, 'quantity': item.quantity,
            'total': item.total
        };
    });
    console.log(joined);

最后如何获得新对象的总属性?我尝试了上述方法,但总值 10 不存在。我在下面尝试了另一个版本,但仍然没有成功。

get total() {
            return this.unitprice * this.quantity
        }

标签: javascript

解决方案


你可以试试:

const products = [
  {
    id: 5,
    productName: "Logitech Mouse",
    unitprice: 35
  },
  {
    id: 6,
    productName: "Logitech Keyboard",
    unitprice: 40
  }
];

const carts = [
  {
    id: 101,
    userId: 3,
    productId: 5,
    quantity: 2,
    total: function () {
      return products.find(product => product.id === this.productId).unitprice * this.quantity;
    }
  }
];

let joined = carts.map(item => {
  console.log(item.total());
  let { id, ...rest } = products.find(p => p.id === item.productId);

  return {
    ...rest, "quantity": item.quantity,
    "total": item.total
  };
});
console.log(joined);


推荐阅读