javascript - 带有方法的属性的 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
}
解决方案
你可以试试:
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);
推荐阅读
- node.js - 为什么不使用 mongoose 将完整的 JSON 发送到 mongodb?
- ruby-on-rails - 从 ID 数组中找出哪些 ID 尚不存在
- getstream-io - 自定义 Stream React 聊天组件样式
- oauth-2.0 - Google Smart Home Actions 将设备“[测试] ACTION 已链接”添加到即时“出了点问题。再试一次'
- c++ - 获得对句柄的访问权限
- c++ - 如何在 Qt 多语言支持中映射正确的语言?
- nosql - 如何将属性标记为 DynamoDBRangeKey 和 DynamoDBIndexHashKey?
- r - 如何将回归线添加到 gganimate 图中?
- html - 媒体查询更改了我不想更改的元素
- php - 在 Mac 上安装了 PHP 7.3,但它仍然呈现 7.1.23